-
Notifications
You must be signed in to change notification settings - Fork 0
/
robot.py
2327 lines (1879 loc) · 101 KB
/
robot.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
# Copyright (c) 2016-2017 Anki, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License in the file LICENSE.txt or at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''Classes and functions relating to an individual Cozmo robot.
The :meth:`cozmo.conn.CozmoConnection.wait_for_robot` method returns an
instance of :class:`Robot` which controls a single Cozmo robot.
The :class:`Robot` class has methods and properties to determine its current
state, control its low-level motors, play animations and start behaviors as
well as performing high-level actions such as detecting faces and picking up
objects.
Each :class:`Robot` has a :attr:`Robot.world` attribute which represents an
instance of a :class:`cozmo.world.World`. This tracks the state of the world
that Cozmo knows about: The objects and faces it's currently observing,
the camera images it's receiving, etc. You can monitor the world instance for
various events that occur, or monitor individual objects directly: The
world instance receives all events that the robot triggers, and nearly all SDK
objects inherit from :class:`cozmo.event.Dispatcher` and therefore inherit
methods such as :meth:`~cozmo.event.Dispatcher.wait_for` and
:meth:`~cozmo.event.Dispatcher.add_event_handler`.
'''
# __all__ should order by constants, event classes, other classes, functions.
__all__ = ['MIN_HEAD_ANGLE', 'MAX_HEAD_ANGLE',
'MIN_LIFT_HEIGHT', 'MIN_LIFT_HEIGHT_MM', 'MAX_LIFT_HEIGHT', 'MAX_LIFT_HEIGHT_MM',
'MIN_LIFT_ANGLE', 'MAX_LIFT_ANGLE',
# Event classes
'EvtRobotReady', 'EvtRobotStateUpdated', 'EvtUnexpectedMovement',
# Helper classes
'LiftPosition', 'UnexpectedMovementSide', 'UnexpectedMovementType',
# Robot Action classes
'DisplayOledFaceImage', 'DockWithCube', 'DriveOffChargerContacts', 'DriveStraight',
'GoToObject', 'GoToPose', 'PerformOffChargerContext', 'PickupObject',
'PlaceObjectOnGroundHere', 'PlaceOnObject', 'PopAWheelie', 'RollCube', 'SayText',
'SetHeadAngle', 'SetLiftHeight', 'TurnInPlace', 'TurnTowardsFace',
# Robot
'Robot']
import asyncio
import collections
import math
import warnings
from . import logger, logger_protocol
from . import action
from . import anim
from . import audio
from . import song
from . import behavior
from . import camera
from . import conn
from . import event
from . import exceptions
from . import lights
from . import objects
from . import util
from . import world
from . import robot_alignment
from ._clad import _clad_to_engine_iface, _clad_to_engine_cozmo, _clad_to_engine_anki, _clad_to_game_cozmo, CladEnumWrapper
#### Events
class EvtRobotReady(event.Event):
'''Generated when the robot has been initialized and is ready for commands.'''
robot = "Robot object representing the robot to command"
class EvtRobotStateUpdated(event.Event):
'''Dispatched whenever the robot's state is updated (multiple times per second).'''
robot = "Robot object representing the robot to command"
class EvtUnexpectedMovement(event.Event):
'''Triggered whenever the robot does not move as expected (typically rotation).'''
robot = "Robot object representing the robot to command"
timestamp = "Robot timestamp for when the unexpected movement occurred"
movement_type = "An UnexpectedMovementType Object representing the type of unexpected movement"
movement_side = "An UnexpectedMovementSide Object representing the side that is obstructing movement"
#### Constants
#: The minimum angle the robot's head can be set to
MIN_HEAD_ANGLE = util.degrees(-25)
#: The maximum angle the robot's head can be set to
MAX_HEAD_ANGLE = util.degrees(44.5)
# The lowest height-above-ground that lift can be moved to in millimeters.
MIN_LIFT_HEIGHT_MM = 32.0
#: The lowest height-above-ground that lift can be moved to
MIN_LIFT_HEIGHT = util.distance_mm(MIN_LIFT_HEIGHT_MM)
# The largest height-above-ground that lift can be moved to in millimeters.
MAX_LIFT_HEIGHT_MM = 92.0
#: The largest height-above-ground that lift can be moved to
MAX_LIFT_HEIGHT = util.distance_mm(MAX_LIFT_HEIGHT_MM)
#: The length of Cozmo's lift arm
LIFT_ARM_LENGTH = util.distance_mm(66.0)
#: The height above ground of Cozmo's lift arm's pivot
LIFT_PIVOT_HEIGHT = util.distance_mm(45.0)
#: The minimum angle the robot's lift can be set to
MIN_LIFT_ANGLE = util.radians(math.asin((MIN_LIFT_HEIGHT_MM - LIFT_PIVOT_HEIGHT.distance_mm) / LIFT_ARM_LENGTH.distance_mm))
#: The maximum angle the robot's lift can be set to
MAX_LIFT_ANGLE = util.radians(math.asin((MAX_LIFT_HEIGHT_MM - LIFT_PIVOT_HEIGHT.distance_mm) / LIFT_ARM_LENGTH.distance_mm))
class LiftPosition:
'''Represents the position of Cozmo's lift.
The class allows the position to be referred to as either absolute height
above the ground, as a ratio from 0.0 to 1.0, or as the angle of the lift
arm relative to the ground.
Args:
height (:class:`cozmo.util.Distance`): The height of the lift above the ground.
ratio (float): The ratio from 0.0 to 1.0 that the lift is raised from the ground.
angle (:class:`cozmo.util.Angle`): The angle of the lift arm relative to the ground.
'''
__slots__ = ('_height')
def __init__(self, height=None, ratio=None, angle=None):
def _count_arg(arg):
# return 1 if argument is set (not None), 0 otherwise
return 0 if (arg is None) else 1
num_provided_args = _count_arg(height) + _count_arg(ratio) + _count_arg(angle)
if num_provided_args != 1:
raise ValueError("Expected one, and only one, of the distance, ratio or angle keyword arguments")
if height is not None:
if not isinstance(height, util.Distance):
raise TypeError("Unsupported type for distance - expected util.Distance")
self._height = height
elif ratio is not None:
height_mm = MIN_LIFT_HEIGHT_MM + (ratio * (MAX_LIFT_HEIGHT_MM - MIN_LIFT_HEIGHT_MM))
self._height = util.distance_mm(height_mm)
elif angle is not None:
if not isinstance(angle, util.Angle):
raise TypeError("Unsupported type for angle - expected util.Angle")
height_mm = (math.sin(angle.radians) * LIFT_ARM_LENGTH.distance_mm) + LIFT_PIVOT_HEIGHT.distance_mm
self._height = util.distance_mm(height_mm)
def __repr__(self):
return "<%s height=%s ratio=%s angle=%s>" % (self.__class__.__name__, self._height, self.ratio, self.angle)
@property
def height(self):
''':class:`cozmo.util.Distance`: The height above the ground.'''
return self._height
@property
def ratio(self):
'''float: The ratio from 0 to 1 that the lift is raised, 0 at the bottom, 1 at the top.'''
ratio = ((self._height.distance_mm - MIN_LIFT_HEIGHT_MM) /
(MAX_LIFT_HEIGHT_MM - MIN_LIFT_HEIGHT_MM))
return ratio
@property
def angle(self):
''':class:`cozmo.util.Angle`: The angle of the lift arm relative to the ground.'''
sin_angle = (self._height.distance_mm - LIFT_PIVOT_HEIGHT.distance_mm) / LIFT_ARM_LENGTH.distance_mm
angle_radians = math.asin(sin_angle)
return util.radians(angle_radians)
#### Actions
class GoToPose(action.Action):
'''Represents the go to pose action in progress.
Returned by :meth:`~cozmo.robot.Robot.go_to_pose`
'''
def __init__(self, pose, **kw):
super().__init__(**kw)
self.pose = pose
def _repr_values(self):
return "pose=%s" % (self.pose)
def _encode(self):
return _clad_to_engine_iface.GotoPose(x_mm=self.pose.position.x,
y_mm=self.pose.position.y,
rad=self.pose.rotation.angle_z.radians)
class GoToObject(action.Action):
'''Represents the go to object action in progress.
Returned by :meth:`~cozmo.robot.Robot.go_to_object`
'''
def __init__(self, object_id, distance_from_object, **kw):
super().__init__(**kw)
self.object_id = object_id
self.distance_from_object = distance_from_object
def _repr_values(self):
return "object_id=%s, distance_from_object=%s" % (self.object_id, self.distance_from_object)
def _encode(self):
return _clad_to_engine_iface.GotoObject(objectID=self.object_id,
distanceFromObjectOrigin_mm=self.distance_from_object.distance_mm,
useManualSpeed=False,
usePreDockPose=False)
class DockWithCube(action.Action):
'''Represents the dock with cube action in progress.
Returned by :meth:`~cozmo.robot.Robot.dock_with_cube`
'''
def __init__(self, obj, approach_angle, alignment_type, distance_from_marker, **kw):
super().__init__(**kw)
#: The object (e.g. an instance of :class:`cozmo.objects.LightCube`) that is being put down
self.obj = obj
self.alignment_type = alignment_type
if approach_angle is None:
self.use_approach_angle = False
self.approach_angle = util.degrees(0)
else:
self.use_approach_angle = True
self.approach_angle = approach_angle
if distance_from_marker is None:
self.distance_from_marker = util.distance_mm(0)
else:
self.distance_from_marker = distance_from_marker
def _repr_values(self):
return "object=%s" % (self.obj)
def _encode(self):
return _clad_to_engine_iface.AlignWithObject(objectID=self.obj.object_id,
distanceFromMarker_mm=self.distance_from_marker.distance_mm,
approachAngle_rad=self.approach_angle.radians,
alignmentType=self.alignment_type.id,
useApproachAngle=self.use_approach_angle,
usePreDockPose=self.use_approach_angle,
useManualSpeed=False)
class RollCube(action.Action):
'''Represents the roll cube action in progress.
Returned by :meth:`~cozmo.robot.Robot.roll_cube`
'''
def __init__(self, obj, approach_angle, check_for_object_on_top, **kw):
super().__init__(**kw)
#: The object (e.g. an instance of :class:`cozmo.objects.LightCube`) that is being put down
self.obj = obj
#: bool: whether to check if there is an object on top
self.check_for_object_on_top = check_for_object_on_top
if approach_angle is None:
self.use_approach_angle = False
self.approach_angle = util.degrees(0)
else:
self.use_approach_angle = True
self.approach_angle = approach_angle
def _repr_values(self):
return "object=%s, check_for_object_on_top=%s, approach_angle=%s" % (self.obj, self.check_for_object_on_top, self.approach_angle)
def _encode(self):
return _clad_to_engine_iface.RollObject(objectID=self.obj.object_id,
approachAngle_rad=self.approach_angle.radians,
useApproachAngle=self.use_approach_angle,
usePreDockPose=self.use_approach_angle,
useManualSpeed=False,
checkForObjectOnTop=self.check_for_object_on_top)
class DriveOffChargerContacts(action.Action):
'''Represents the drive off charger contacts action in progress.
Returned by :meth:`~cozmo.robot.Robot.drive_off_charger_contacts`
'''
def __init__(self, **kw):
super().__init__(**kw)
def _repr_values(self):
return ""
def _encode(self):
return _clad_to_engine_iface.DriveOffChargerContacts()
class DriveStraight(action.Action):
'''Represents the "drive straight" action in progress.
Returned by :meth:`~cozmo.robot.Robot.drive_straight`
'''
def __init__(self, distance, speed, should_play_anim, **kw):
super().__init__(**kw)
#: :class:`cozmo.util.Distance`: The distance to drive
self.distance = distance
#: :class:`cozmo.util.Speed`: The speed to drive at
self.speed = speed
#: bool: Whether to play an animation whilst driving
self.should_play_anim = should_play_anim
def _repr_values(self):
return "distance=%s speed=%s should_play_anim=%s" % (self.distance, self.speed, self.should_play_anim)
def _encode(self):
return _clad_to_engine_iface.DriveStraight(speed_mmps=self.speed.speed_mmps,
dist_mm=self.distance.distance_mm,
shouldPlayAnimation=self.should_play_anim)
class DisplayOledFaceImage(action.Action):
'''Represents the "display oled face image" action in progress.
Returned by :meth:`~cozmo.robot.Robot.display_oled_face_image`
'''
# Face images are sent so frequently, with the previous face image always
# aborted, that logging each event would spam the log.
_enable_abort_logging = False
def __init__(self, screen_data, duration_ms, **kw):
super().__init__(**kw)
#: :class:`bytes`: a sequence of pixels (8 pixels per byte)
self.screen_data = screen_data
#: float: time to keep displaying this image on Cozmo's face
self.duration_ms = duration_ms
def _repr_values(self):
return "screen_data=%s Bytes duration_ms=%s" %\
(len(self.screen_data), self.duration_ms)
def _encode(self):
return _clad_to_engine_iface.DisplayFaceImage(faceData=self.screen_data,
duration_ms=self.duration_ms)
class PickupObject(action.Action):
'''Represents the pickup object action in progress.
Returned by :meth:`~cozmo.robot.Robot.pickup_object`
'''
def __init__(self, obj, use_pre_dock_pose=True, **kw):
super().__init__(**kw)
#: The object (e.g. an instance of :class:`cozmo.objects.LightCube`) that was picked up
self.obj = obj
#: A bool that is true when Cozmo needs to go to a pose before attempting to navigate to the object
self.use_pre_dock_pose = use_pre_dock_pose
def _repr_values(self):
return "object=%s" % (self.obj,)
def _encode(self):
return _clad_to_engine_iface.PickupObject(objectID=self.obj.object_id,
usePreDockPose=self.use_pre_dock_pose)
class PlaceOnObject(action.Action):
'''Tracks the state of the "place on object" action.
return by :meth:`~cozmo.robot.Robot.place_on_object`
'''
def __init__(self, obj, use_pre_dock_pose=True, **kw):
super().__init__(**kw)
#: The object (e.g. an instance of :class:`cozmo.objects.LightCube`) that the held object will be placed on
self.obj = obj
#: A bool that is true when Cozmo needs to go to a pose before attempting to navigate to the object
self.use_pre_dock_pose = use_pre_dock_pose
def _repr_values(self):
return "object=%s use_pre_dock_pose=%s" % (self.obj, self.use_pre_dock_pose)
def _encode(self):
return _clad_to_engine_iface.PlaceOnObject(objectID=self.obj.object_id,
usePreDockPose=self.use_pre_dock_pose)
class PlaceObjectOnGroundHere(action.Action):
'''Tracks the state of the "place object on ground here" action.
Returned by :meth:`~cozmo.robot.Robot.place_object_on_ground_here`
'''
def __init__(self, obj, **kw):
super().__init__(**kw)
#: The object (e.g. an instance of :class:`cozmo.objects.LightCube`) that is being put down
self.obj = obj
def _repr_values(self):
return "object=%s" % (self.obj,)
def _encode(self):
return _clad_to_engine_iface.PlaceObjectOnGroundHere()
class SayText(action.Action):
'''Tracks the progress of a say text robot action.
Returned by :meth:`~cozmo.robot.Robot.say_text`
'''
def __init__(self, text, play_excited_animation, use_cozmo_voice, duration_scalar, voice_pitch, **kw):
super().__init__(**kw)
self.text = text
# Note: play_event must be an AnimationTrigger that supports text-to-speech being generated
if play_excited_animation:
self.play_event = _clad_to_engine_cozmo.AnimationTrigger.OnSawNewNamedFace
else:
# TODO: Switch to use AnimationTrigger.SdkTextToSpeech when that works correctly
self.play_event = _clad_to_engine_cozmo.AnimationTrigger.Count
if use_cozmo_voice:
self.say_style = _clad_to_engine_cozmo.SayTextVoiceStyle.CozmoProcessing_Sentence
else:
# default male human voice
self.say_style = _clad_to_engine_cozmo.SayTextVoiceStyle.Unprocessed
self.duration_scalar = duration_scalar
self.voice_pitch = voice_pitch
def _repr_values(self):
return "text='%s' style=%s event=%s duration=%s pitch=%s" %\
(self.text, self.say_style, self.play_event, self.duration_scalar, self.voice_pitch)
def _encode(self):
return _clad_to_engine_iface.SayText(text=self.text,
playEvent=self.play_event,
voiceStyle=self.say_style,
durationScalar=self.duration_scalar,
voicePitch=self.voice_pitch,
fitToDuration=False)
class SetHeadAngle(action.Action):
'''Represents the Set Head Angle action in progress.
Returned by :meth:`~cozmo.robot.Robot.set_head_angle`
'''
def __init__(self, angle, max_speed, accel, duration, warn_on_clamp, **kw):
super().__init__(**kw)
if angle < MIN_HEAD_ANGLE:
if warn_on_clamp:
logger.warning("Clamping head angle from %s to min %s" % (angle, MIN_HEAD_ANGLE))
self.angle = MIN_HEAD_ANGLE
elif angle > MAX_HEAD_ANGLE:
if warn_on_clamp:
logger.warning("Clamping head angle from %s to max %s" % (angle, MAX_HEAD_ANGLE))
self.angle = MAX_HEAD_ANGLE
else:
self.angle = angle
#: float: Maximum speed of Cozmo's head in radians per second
self.max_speed = max_speed
#: float: Acceleration of Cozmo's head in radians per second squared
self.accel = accel
#: float: Time for Cozmo's head to turn in seconds
self.duration = duration
def _repr_values(self):
return "angle=%s max_speed=%s accel=%s duration=%s" %\
(self.angle, self.max_speed, self.accel, self.duration)
def _encode(self):
return _clad_to_engine_iface.SetHeadAngle(angle_rad=self.angle.radians,
max_speed_rad_per_sec=self.max_speed,
accel_rad_per_sec2=self.accel,
duration_sec=self.duration)
class SetLiftHeight(action.Action):
'''Represents the Set Lift Height action in progress.
Returned by :meth:`~cozmo.robot.Robot.set_lift_height`
'''
def __init__(self, height, max_speed, accel, duration, **kw):
super().__init__(**kw)
if height < 0.0:
logger.warning("lift height %s too small, should be in 0..1 range - clamping", height)
self.lift_height_mm = MIN_LIFT_HEIGHT_MM
elif height > 1.0:
logger.warning("lift height %s too large, should be in 0..1 range - clamping", height)
self.lift_height_mm = MAX_LIFT_HEIGHT_MM
else:
self.lift_height_mm = MIN_LIFT_HEIGHT_MM + (height * (MAX_LIFT_HEIGHT_MM - MIN_LIFT_HEIGHT_MM))
#: float: Maximum speed of Cozmo's lift in radians per second
self.max_speed = max_speed
#: float: Acceleration of Cozmo's lift in radians per second squared
self.accel = accel
#: float: Time for Cozmo's lift to turn in seconds
self.duration = duration
def _repr_values(self):
return "height=%s max_speed=%s accel=%s duration=%s" %\
(self.lift_height_mm, self.max_speed, self.accel, self.duration)
def _encode(self):
return _clad_to_engine_iface.SetLiftHeight(height_mm=self.lift_height_mm,
max_speed_rad_per_sec=self.max_speed,
accel_rad_per_sec2=self.accel,
duration_sec=self.duration)
class TurnInPlace(action.Action):
'''Tracks the progress of a turn in place robot action.
Returned by :meth:`~cozmo.robot.Robot.turn_in_place`
'''
def __init__(self, angle, speed, accel, angle_tolerance, is_absolute, **kw):
super().__init__(**kw)
#: :class:`cozmo.util.Angle`: The angle to turn
self.angle = angle
#: :class:`cozmo.util.Angle`: Angular turn speed (per second).
self.speed = speed
#: :class:`cozmo.util.Angle`: Acceleration of angular turn (per second squared).
self.accel = accel
#: :class:`cozmo.util.Angle`: The minimum angular tolerance to consider
#: the action complete (this is clamped to a minimum of 2 degrees internally).
self.angle_tolerance = angle_tolerance
#: bool: True to turn to a specific angle, False to turn relative to the current pose.
self.is_absolute = is_absolute
def _repr_values(self):
return "angle=%s, speed=%s, accel=%s, tolerance=%s is_absolute=%s" %\
(self.angle, self.speed, self.accel, self.angle_tolerance, self.is_absolute)
def _get_radians(self, in_angle, default_value=0.0):
# Helper method to allow None angles to represent default values
if in_angle is None:
return default_value
else:
return in_angle.radians
def _encode(self):
return _clad_to_engine_iface.TurnInPlace(
angle_rad = self.angle.radians,
speed_rad_per_sec = self._get_radians(self.speed),
accel_rad_per_sec2 = self._get_radians(self.accel),
tol_rad = self._get_radians(self.angle_tolerance),
isAbsolute = int(self.is_absolute))
class PopAWheelie(action.Action):
'''Tracks the progress of a "pop a wheelie" robot action.
Returned by :meth:`~cozmo.robot.Robot.pop_a_wheelie`
'''
def __init__(self, obj, approach_angle, **kw):
super().__init__(**kw)
#: An object (e.g. an instance of :class:`cozmo.objects.LightCube`)
#: being used as leverage to push cozmo on his back
self.obj = obj
if approach_angle is None:
self.use_approach_angle = False
self.approach_angle = util.degrees(0)
else:
self.use_approach_angle = True
self.approach_angle = approach_angle
def _repr_values(self):
return ("object=%s, use_approach_angle=%s, approach_angle=%s" %
(self.obj, self.use_approach_angle, self.approach_angle) )
def _encode(self):
return _clad_to_engine_iface.PopAWheelie(
objectID=self.obj.object_id,
approachAngle_rad=self.approach_angle.radians,
useApproachAngle=self.use_approach_angle,
usePreDockPose=self.use_approach_angle,
useManualSpeed=False)
class TurnTowardsFace(action.Action):
'''Tracks the progress of a turn towards face robot action.
Returned by :meth:`~cozmo.robot.Robot.turn_towards_face`
'''
def __init__(self, face, **kw):
super().__init__(**kw)
#: :class:`~cozmo.faces.Face`: The face to turn towards
self.face = face
def _repr_values(self):
return "face=%s" % (self.face)
def _encode(self):
return _clad_to_engine_iface.TurnTowardsFace(
faceID=self.face.face_id,
maxTurnAngle_rad=util.degrees(180).radians)
class PerformOffChargerContext(event.Dispatcher):
'''A helper class to provide a context manager to do operations while Cozmo is off charger.'''
def __init__(self, robot, **kw):
super().__init__(**kw)
self.robot = robot
async def __aenter__(self):
self.was_on_charger = self.robot.is_on_charger
if self.was_on_charger:
await self.robot.drive_off_charger_contacts(in_parallel=True).wait_for_completed()
return self
async def __aexit__(self, exc_type, exc_value, traceback):
if self.was_on_charger:
await self.robot.backup_onto_charger()
return False
class Robot(event.Dispatcher):
"""The interface to a Cozmo robot.
A robot has access to:
* A :class:`~cozmo.world.World` object (:attr:`cozmo.robot.Robot.world`),
which tracks the state of the world the robot knows about
* A :class:`~cozmo.camera.Camera` object (:attr:`cozmo.robot.Robot.camera`),
which provides access to Cozmo's camera
* An Animations object, controlling the playing of animations on the robot
* A Behaviors object, starting and ending robot behaviors such as looking around
Robots are instantiated by the :class:`~cozmo.conn.CozmoConnection` object
and emit a :class:`EvtRobotReady` when it has been configured and is
ready to be commanded.
"""
# action factories
_action_dispatcher_factory = action._ActionDispatcher
#: callable: The factory function that returns a
#: :class:`TurnInPlace` class or subclass instance.
turn_in_place_factory = TurnInPlace
#: callable: The factory function that returns a
#: :class:`TurnTowardsFace` class or subclass instance.
turn_towards_face_factory = TurnTowardsFace
#: callable: The factory function that returns a
#: :class:`PickupObject` class or subclass instance.
pickup_object_factory = PickupObject
#: callable: The factory function that returns a
#: :class:`PlaceOnObject` class or subclass instance.
place_on_object_factory = PlaceOnObject
#: callable: The factory function that returns a
#: :class:`GoToPose` class or subclass instance.
go_to_pose_factory = GoToPose
#: callable: The factory function that returns a
#: :class:`GoToObject` class or subclass instance.
go_to_object_factory = GoToObject
#: callable: The factory function that returns a
#: :class:`DockWithCube` class or subclass instance.
dock_with_cube_factory = DockWithCube
#: callable: The factory function that returns a
#: :class:`RollCube` class or subclass instance.
roll_cube_factory = RollCube
#: callable: The factory function that returns a
#: :class:`PlaceObjectOnGroundHere` class or subclass instance.
place_object_on_ground_here_factory = PlaceObjectOnGroundHere
#: callable: The factory function that returns a
#: :class:`PopAWheelie` class or subclass instance.
pop_a_wheelie_factory = PopAWheelie
#: callable: The factory function that returns a
#: :class:`SayText` class or subclass instance.
say_text_factory = SayText
#: callable: The factory function that returns a
#: :class:`SetHeadAngle` class or subclass instance.
set_head_angle_factory = SetHeadAngle
#: callable: The factory function that returns a
#: :class:`SetLiftHeight` class or subclass instance.
set_lift_height_factory = SetLiftHeight
#: callable: The factory function that returns a
#: :class:`DriveOffChargerContacts` class or subclass instance.
drive_off_charger_contacts_factory = DriveOffChargerContacts
#: callable: The factory function that returns a
#: :class:`DriveStraight` class or subclass instance.
drive_straight_factory = DriveStraight
#: callable: The factory function that returns a
#: :class:`DisplayOledFaceImage` class or subclass instance.
display_oled_face_image_factory = DisplayOledFaceImage
# other factories
#: callable: The factory function that returns a
#: :class:`cozmo.anim.Animation` class or subclass instance.
animation_factory = anim.Animation
#: callable: The factory function that returns a
#: :class:`cozmo.anim.AnimationTrigger` class or subclass instance.
animation_trigger_factory = anim.AnimationTrigger
#: callable: The factory function that returns a
#: :class:`cozmo.behavior.Behavior` class or subclass instance.
behavior_factory = behavior.Behavior
#: callable: The factory function that returns a
#: :class:`cozmo.camera.Camera` class or subclass instance.
camera_factory = camera.Camera
#: callable: The factory function that returns a
#: :class:`cozmo.robot.PerformOffChargerContext` class or subclass instance.
perform_off_charger_factory = PerformOffChargerContext
#: callable: The factory function that returns a
#: :class:`cozmo.world.World` class or subclass instance.
world_factory = world.World
# other attributes
#: bool: Set to True if the robot should drive off the charger as soon
#: as the SDK connects to the engine. Defaults to True.
drive_off_charger_on_connect = True # Required for most movement actions
_current_behavior = None # type: Behavior
_is_freeplay_mode_active = False
def __init__(self, conn, robot_id: int, is_primary: bool, **kw):
super().__init__(**kw)
#: :class:`cozmo.conn.CozmoConnection`: The active connection to the engine.
self.conn = conn # type: conn.CozmoConnection
#: int: The internal ID number of the robot.
self.robot_id = robot_id
self._is_ready = False
self._pose = None # type: util.Pose
#: bool: Specifies that this is the primary robot (always True currently)
self.is_primary = is_primary
#: :class:`cozmo.camera.Camera`: Provides access to the robot's camera
self.camera = self.camera_factory(self, dispatch_parent=self)
#: :class:`cozmo.world.World`: Tracks state information about Cozmo's world.
self.world = self.world_factory(self.conn, self, dispatch_parent=self)
self._action_dispatcher = self._action_dispatcher_factory(self)
self._current_face_image_action = None # type: DisplayOledFaceImage
#: :class:`cozmo.util.Speed`: Speed of the left wheel
self.left_wheel_speed = None # type: util.Speed
#: :class:`cozmo.util.Speed`: Speed of the right wheel
self.right_wheel_speed = None # type: util.Speed
self._lift_position = LiftPosition(height=util.distance_mm(MIN_LIFT_HEIGHT_MM))
#: float: The current battery voltage (not linear, but < 3.5 is low)
self.battery_voltage = None # type: float
#: :class:`cozmo.util.Vector3`: The current accelerometer reading (x,y,z)
#: In mm/s^2, measured in Cozmo's head (e.g. x=0 when Cozmo's head is level
#: but x = z = ~7000 mm/s^2 when Cozmo's head is angled 45 degrees up)
self.accelerometer = None # type: util.Vector3
self._is_device_accelerometer_supported = None # type: bool
self._is_device_gyro_supported = None # type: bool
#: :class:`cozmo.util.Vector3`: The current accelerometer reading for
#: the connected mobile device. Requires that you have first called
#: :meth:`enable_device_imu` with `enable_raw = True`. See
#: :attr:`device_accel_user` for a user-filtered equivalent.
self.device_accel_raw = None # type: util.Vector3
#: :class:`cozmo.util.Vector3`: The current user-filtered accelerometer
#: reading for the connected mobile device. Requires that you have first
#: called :meth:`enable_device_imu` with `enable_user = True`. This
#: filtered version removes the constant acceleration from Gravity. See
#: :attr:`device_accel_raw` for a raw version.
self.device_accel_user = None # type: util.Vector3
#: :class:`cozmo.util.Quaternion`: The current gyro reading for
#: the connected mobile device. Requires that you have first called
#: :meth:`enable_device_imu` with `enable_gyro = True`
self.device_gyro = None # type: util.Quaternion
#: :class:`cozmo.util.Vector3`: The current gyro reading (x,y,z)
#: In radians/s, measured in Cozmo's head.
#: Therefore a large value in a given component would indicate Cozmo is
#: being rotated around that axis (where x=forward, y=left, z=up), e.g.
#: y = -5 would indicate that Cozmo is being rolled onto his back
self.gyro = None # type: util.Vector3
#: int: The ID of the object currently being carried (-1 if none)
self.carrying_object_id = -1
#: int: The ID of the object on top of the object currently being carried (-1 if none)
self.carrying_object_on_top_id = -1
#: int: The ID of the object the head is tracking to (-1 if none)
self.head_tracking_object_id = -1
#: int: The ID of the object that the robot is localized to (-1 if none)
self.localized_to_object_id = -1
#: int: The robot's timestamp for the last image seen.
#: ``None`` if no image was received yet.
#: In milliseconds relative to robot epoch.
self.last_image_robot_timestamp = None # type: int
self._pose_angle = None # type: util.Angle
self._pose_pitch = None # type: util.Angle
self._head_angle = None # type: util.Angle
self._robot_status_flags = 0
self._game_status_flags = 0
self._serial_number_head = 0
self._serial_number_body = 0
self._model_number = 0
self._hw_version = 0
# send all received events to the world and action dispatcher
self._add_child_dispatcher(self._action_dispatcher)
self._add_child_dispatcher(self.world)
#### Private Methods ####
def _initialize(self):
# Perform all steps necessary to initialize the robot and trigger
# an EvtRobotReady event when complete.
async def _init():
# Note: Robot state is reset on entering SDK mode, and after any SDK program exits
self.stop_all_motors()
self.enable_all_reaction_triggers(False)
self.enable_stop_on_cliff(True)
self._set_none_behavior()
# Default to no memory map data being streamed
self.world.request_nav_memory_map(-1.0)
# Default to no device IMU data being streamed
self.enable_device_imu(False, False, False)
# Ensure the SDK has full control of cube lights
self._set_cube_light_state(False)
await self.world.delete_all_custom_objects()
# wait for animations to load
await self.conn.anim_names.wait_for_loaded()
msg = _clad_to_engine_iface.GetBlockPoolMessage()
self.conn.send_msg(msg)
self._is_ready = True
logger.info('Robot id=%s serial=%s initialized OK', self.robot_id, self.serial)
self.dispatch_event(EvtRobotReady, robot=self)
self._idle_stack_depth = 0
self.set_idle_animation(anim.Triggers.Count)
asyncio.ensure_future(_init(), loop=self._loop)
def _set_none_behavior(self):
# Internal helper method called from Behavior.stop etc.
msg = _clad_to_engine_iface.ExecuteBehaviorByExecutableType(
behaviorType=_clad_to_engine_cozmo.ExecutableBehaviorType.Wait)
self.conn.send_msg(msg)
if self._current_behavior is not None:
self._current_behavior._set_stopped()
def _set_cube_light_state(self, enable):
msg = _clad_to_engine_iface.EnableLightStates(enable=enable, objectID=-1)
self.conn.send_msg(msg)
def _enable_cube_sleep(self, enable=True, skip_animation=True):
# skip_animation (bool): True to skip the fadeout part of the sleep anim
msg = _clad_to_engine_iface.EnableCubeSleep(enable=enable,
skipAnimation=skip_animation)
self.conn.send_msg(msg)
#### Properties ####
@property
def is_ready(self):
"""bool: True if the robot has been initialized and is ready to accept commands."""
return self._is_ready
@property
def anim_names(self):
'''set of string: Set of all the available animation names
An alias of :attr:`cozmo.conn.anim_names`.
Generally animation triggers are preferred over explict animation names:
See :class:`cozmo.anim.Triggers` for available animation triggers.
'''
return self.conn.anim_names
@property
def anim_triggers(self):
'''list of :class:`cozmo.anim.Triggers`, specifying available animation triggers
These can be sent to the play_anim_trigger to make the robot perform animations.
An alias of :attr:`cozmo.anim.Triggers.trigger_list`.
'''
return anim.Triggers.trigger_list
@property
def pose(self):
""":class:`cozmo.util.Pose`: The current pose (position and orientation) of Cozmo
"""
return self._pose
@property
def is_moving(self):
'''bool: True if Cozmo is currently moving anything (head, lift or wheels/treads).'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.IS_MOVING) != 0
@property
def is_carrying_block(self):
'''bool: True if Cozmo is currently carrying a block.'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.IS_CARRYING_BLOCK) != 0
@property
def is_picking_or_placing(self):
'''bool: True if Cozmo is picking or placing something.'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.IS_PICKING_OR_PLACING) != 0
@property
def is_picked_up(self):
'''bool: True if Cozmo is currently picked up (in the air).'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.IS_PICKED_UP) != 0
@property
def is_falling(self):
'''bool: True if Cozmo is currently falling.'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.IS_FALLING) != 0
@property
def is_animating(self):
'''bool: True if Cozmo is currently playing an animation.'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.IS_ANIMATING) != 0
@property
def is_animating_idle(self):
'''bool: True if Cozmo is currently playing an idle animation.'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.IS_ANIMATING_IDLE) != 0
@property
def is_pathing(self):
'''bool: True if Cozmo is currently traversing a path.'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.IS_PATHING) != 0
@property
def is_lift_in_pos(self):
'''bool: True if Cozmo's lift is in the desired position (False if still trying to move there).'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.LIFT_IN_POS) != 0
@property
def is_head_in_pos(self):
'''bool: True if Cozmo's head is in the desired position (False if still trying to move there).'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.HEAD_IN_POS) != 0
@property
def is_anim_buffer_full(self):
'''bool: True if Cozmo's animation buffer is full (on robot).'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.IS_ANIM_BUFFER_FULL) != 0
@property
def is_on_charger(self):
'''bool: True if Cozmo is currently on the charger.'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.IS_ON_CHARGER) != 0
@property
def is_charging(self):
'''bool: True if Cozmo is currently charging.'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.IS_CHARGING) != 0
@property
def is_cliff_detected(self):
'''bool: True if Cozmo detected a cliff (in front of the robot).'''
return (self._robot_status_flags & _clad_to_game_cozmo.RobotStatusFlag.CLIFF_DETECTED) != 0