forked from anki/vector-python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjects.py
More file actions
1658 lines (1230 loc) · 62.4 KB
/
objects.py
File metadata and controls
1658 lines (1230 loc) · 62.4 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) 2018 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
#
# https://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.
"""Object and Light Cube recognition.
Vector can recognize and track a number of different types of objects.
These objects may be visible (currently observed by the robot's camera)
and tappable (in the case of the Light Cube that ships with the robot).
The Light Cube is known as a :class:`LightCube` by the SDK. The cube
has controllable lights, and sensors that can determine when it's being
moved or tapped.
Objects can generate events which can be subscribed to from the anki_vector.events
class, such as object_appeared (of type EvtObjectAppeared), and
object_disappeared (of type EvtObjectDisappeared), which are broadcast
based on both robot originating events and local state.
All observable objects have a marker of a known size attached to them, which allows Vector
to recognize the object and its position and rotation ("pose"). You can attach
markers to your own objects for Vector to recognize by printing them out from the
online documentation. They will be detected as :class:`CustomObject` instances.
Vector connects to his Light Cubes with BLE.
"""
# __all__ should order by constants, event classes, other classes, functions.
__all__ = ['LIGHT_CUBE_1_TYPE', 'OBJECT_VISIBILITY_TIMEOUT',
'EvtObjectAppeared', 'EvtObjectDisappeared', 'EvtObjectFinishedMove', 'EvtObjectObserved',
'Charger', 'CustomObjectArchetype', 'CustomObject', 'CustomObjectMarkers', 'CustomObjectTypes',
'FixedCustomObject', 'LightCube', 'ObservableObject']
# TODO Curious why events like the following aren't listed? At least some do seem to be supported in other parts of anki_vector.
# EvtObjectTapped, EvtObjectConnectChanged, EvtObjectConnected, EvtObjectLocated, EvtObjectMoving, EvtObjectMovingStarted
import collections
import math
import time
from . import connection, lights, util
from .events import Events
from .messaging import protocol
#: Length of time in seconds to go without receiving an observed event before
#: assuming that Vector can no longer see an object.
OBJECT_VISIBILITY_TIMEOUT = 0.8
class EvtObjectObserved(): # pylint: disable=too-few-public-methods
"""Triggered whenever an object is visually identified by the robot.
A stream of these events are produced while an object is visible to the robot.
Each event has an updated image_box field.
See EvtObjectAppeared if you only want to know when an object first
becomes visible.
:param obj: The object that was observed
:param image_rect: An :class:`anki_vector.util.ImageRect`: defining where the object is within Vector's camera view
:param pose: The :class:`anki_vector.util.Pose`: defining the position and rotation of the object
"""
def __init__(self, obj, image_rect: util.ImageRect, pose: util.Pose):
self.obj = obj
self.image_rect = image_rect
self.pose = pose
class EvtObjectAppeared(): # pylint: disable=too-few-public-methods
"""Triggered whenever an object is first visually identified by a robot.
This differs from EvtObjectObserved in that it's only triggered when
an object initially becomes visible. If it disappears for more than
OBJECT_VISIBILITY_TIMEOUT seconds and then is seen again, a
EvtObjectDisappeared will be dispatched, followed by another
EvtObjectAppeared event.
For continuous tracking information about a visible object, see
EvtObjectObserved.
:param obj: The object that is starting to be observed
:param image_rect: An :class:`anki_vector.util.ImageRect`: defining where the object is within Vector's camera view
:param pose: The :class:`anki_vector.util.Pose`: defining the position and rotation of the object
"""
def __init__(self, obj, image_rect: util.ImageRect, pose: util.Pose):
self.obj = obj
self.image_rect = image_rect
self.pose = pose
class EvtObjectDisappeared(): # pylint: disable=too-few-public-methods
"""Triggered whenever an object that was previously being observed is no longer visible.
:param obj: The object that is no longer being observed
"""
def __init__(self, obj):
self.obj = obj
class EvtObjectFinishedMove(): # pylint: disable=too-few-public-methods
"""Triggered when an active object stops moving.
:param obj: The object that moved
:param move_duration: The duration of the move
"""
def __init__(self, obj, move_duration: float):
self.obj = obj
self.move_duration = move_duration
class ObservableObject(util.Component):
"""Represents any object Vector can see in the world."""
visibility_timeout = OBJECT_VISIBILITY_TIMEOUT
def __init__(self, robot, **kw):
super().__init__(robot, **kw)
self._pose: util.Pose = None
#: The time the last event was received.
#: ``None`` if no events have yet been received.
self._last_event_time: float = None
#: The time the element was last observed by the robot.
#: ``None`` if the element has not yet been observed.
self._last_observed_time: float = None
#: The robot's timestamp of the last observed event.
#: ``None`` if the element has not yet been observed.
#: In milliseconds relative to robot epoch.
self._last_observed_robot_timestamp: int = None
#: The ImageRect defining where the
#: object was last visible within Vector's camera view.
#: ``None`` if the element has not yet been observed.
self._last_observed_image_rect: util.ImageRect = None
self._is_visible: bool = False
self._observed_timeout_handler: callable = None
def __repr__(self):
extra = self._repr_values()
if extra:
extra = ' ' + extra
if self.pose:
extra += ' pose=%s' % self.pose
return '<%s%s is_visible=%s>' % (self.__class__.__name__,
extra, self.is_visible)
#### Properties ####
@property
def pose(self) -> util.Pose:
"""The pose of this object in the world.
Is ``None`` for elements that don't have pose information.
.. testcode::
import anki_vector
import time
# First, place a cube directly in front of Vector so he can observe it.
with anki_vector.Robot() as robot:
connectionResult = robot.world.connect_cube()
connected_cube = robot.world.connected_light_cube
for _ in range(16):
connected_cube = robot.world.connected_light_cube
if connected_cube:
print(connected_cube)
print("last observed timestamp: " + str(connected_cube.last_observed_time) + ", robot timestamp: " + str(connected_cube.last_observed_robot_timestamp))
print(robot.world.connected_light_cube.pose)
time.sleep(0.5)
"""
return self._pose
@property
def last_event_time(self) -> float:
"""Time this object last received an event from Vector."""
return self._last_event_time
@property
def last_observed_time(self) -> float:
"""Time this object was last seen."""
return self._last_observed_time
@property
def last_observed_robot_timestamp(self) -> int:
"""Time this object was last seen according to Vector's time."""
return self._last_observed_robot_timestamp
@property
def time_since_last_seen(self) -> float:
"""Time since this object was last seen. math.inf if never seen.
.. testcode::
import anki_vector
with anki_vector.Robot(enable_face_detection=True) as robot:
for face in robot.world.visible_faces:
print(f"time_since_last_seen: {face.time_since_last_seen}")
"""
if self._last_observed_time is None:
return math.inf
return time.time() - self._last_observed_time
@property
def last_observed_image_rect(self) -> util.ImageRect:
"""The location in 2d camera space where this object was last seen."""
return self._last_observed_image_rect
@property
def is_visible(self) -> bool:
"""True if the element has been observed recently, False otherwise.
"recently" is defined as :attr:`visibility_timeout` seconds.
"""
return self._is_visible
#### Private Methods ####
def _repr_values(self): # pylint: disable=no-self-use
return ''
def _reset_observed_timeout_handler(self):
if self._observed_timeout_handler is not None:
self._observed_timeout_handler.cancel()
self._observed_timeout_handler = self.conn.loop.call_later(self.visibility_timeout, self._observed_timeout)
def _observed_timeout(self):
# Triggered when the element is no longer considered "visible".
# i.e. visibility_timeout seconds after the last observed event.
self._is_visible = False
self.conn.run_soon(self._robot.events.dispatch_event(EvtObjectDisappeared(self), Events.object_disappeared))
def _on_observed(self, pose: util.Pose, image_rect: util.ImageRect, robot_timestamp: int):
# Called from subclasses on their corresponding observed messages.
newly_visible = self._is_visible is False
self._is_visible = True
now = time.time()
self._last_observed_time = now
self._last_observed_robot_timestamp = robot_timestamp
self._last_event_time = now
self._last_observed_image_rect = image_rect
self._pose = pose
self._reset_observed_timeout_handler()
self.conn.run_soon(self._robot.events.dispatch_event(EvtObjectObserved(self, image_rect, pose), Events.object_observed))
if newly_visible:
self.conn.run_soon(self._robot.events.dispatch_event(EvtObjectAppeared(self, image_rect, pose), Events.object_appeared))
#: LIGHT_CUBE_1_TYPE's markers look like 2 concentric circles with lines and gaps.
LIGHT_CUBE_1_TYPE = protocol.ObjectType.Value("BLOCK_LIGHTCUBE1")
class LightCube(ObservableObject):
"""Represents Vector's Cube.
The LightCube object has four LEDs that Vector can actively manipulate and communicate with.
As Vector drives around, he uses the position of objects that he recognizes, including his cube,
to localize himself, taking note of the :class:`anki_vector.util.Pose` of the objects.
You can subscribe to cube events including :class:`anki_vector.events.Events.object_tapped`,
:class:`anki_vector.events.Events.object_appeared`, and :class:`anki_vector.events.Events.object_disappeared`.
Vector supports 1 LightCube.
See parent class :class:`ObservableObject` for additional properties
and methods.
"""
#: Length of time in seconds to go without receiving an observed event before
#: assuming that Vector can no longer see an object. Can be overridden in subclasses.
visibility_timeout = OBJECT_VISIBILITY_TIMEOUT
def __init__(self, robot, **kw):
super().__init__(robot, **kw)
#: The time the object was last tapped.
#: ``None`` if the cube wasn't tapped yet.
self._last_tapped_time: float = None
#: The robot's timestamp of the last tapped event.
#: ``None`` if the cube wasn't tapped yet.
#: In milliseconds relative to robot epoch.
self._last_tapped_robot_timestamp: int = None
#: The time the object was last moved.
#: ``None`` if the cube wasn't moved yet.
self._last_moved_time: float = None
#: The robot's timestamp of the last move event.
#: ``None`` if the cube wasn't moved yet.
#: In milliseconds relative to robot epoch.
self._last_moved_robot_timestamp: int = None
#: The time the object started moving when last moved.
self._last_moved_start_time: float = None
#: The robot's timestamp of when the object started moving when last moved.
#: ``None`` if the cube wasn't moved yet.
#: In milliseconds relative to robot epoch.
self._last_moved_start_robot_timestamp: int = None
#: The time the last up axis event was received.
#: ``None`` if no events have yet been received.
self._last_up_axis_changed_time: float = None
#: The robot's timestamp of the last up axis event.
#: ``None`` if the there has not been an up axis event.
#: In milliseconds relative to robot epoch.
self._last_up_axis_changed_robot_timestamp: int = None
# The object's up_axis value from the last time it changed.
self._up_axis: protocol.UpAxis = None
#: True if the cube's accelerometer indicates that the cube is moving.
self._is_moving: bool = False
#: True if the cube is currently connected to the robot via radio.
self._is_connected: bool = False
#: angular distance from the current reported up axis
#: ``None`` if the object has not yet been observed.
self._top_face_orientation_rad: float = None
self._object_id: str = None
#: unique identification of the physical cube
self._factory_id: str = None
#: Subscribe to relevant events
self.robot.events.subscribe(
self._on_object_connection_state_changed,
Events.object_connection_state)
self.robot.events.subscribe(
self._on_object_moved,
Events.object_moved)
self.robot.events.subscribe(
self._on_object_stopped_moving,
Events.object_stopped_moving)
self.robot.events.subscribe(
self._on_object_up_axis_changed,
Events.object_up_axis_changed)
self.robot.events.subscribe(
self._on_object_tapped,
Events.object_tapped)
self.robot.events.subscribe(
self._on_object_observed,
Events.robot_observed_object)
self.robot.events.subscribe(
self._on_object_connection_lost,
Events.cube_connection_lost)
#### Public Methods ####
def teardown(self):
"""All faces will be torn down by the world when no longer needed."""
self.robot.events.unsubscribe(
self._on_object_connection_state_changed,
Events.object_connection_state)
self.robot.events.unsubscribe(
self._on_object_moved,
Events.object_moved)
self.robot.events.unsubscribe(
self._on_object_stopped_moving,
Events.object_stopped_moving)
self.robot.events.unsubscribe(
self._on_object_up_axis_changed,
Events.object_up_axis_changed)
self.robot.events.unsubscribe(
self._on_object_tapped,
Events.object_tapped)
self.robot.events.unsubscribe(
self._on_object_observed,
Events.robot_observed_object)
self.robot.events.unsubscribe(
self._on_object_connection_lost,
Events.cube_connection_lost)
@connection.on_connection_thread()
async def set_light_corners(self,
light1: lights.Light,
light2: lights.Light,
light3: lights.Light,
light4: lights.Light,
color_profile: lights.ColorProfile = lights.WHITE_BALANCED_CUBE_PROFILE):
"""Set the light for each corner.
.. testcode::
import anki_vector
import time
with anki_vector.Robot() as robot:
robot.world.connect_cube()
if robot.world.connected_light_cube:
cube = robot.world.connected_light_cube
cube.set_light_corners(anki_vector.lights.blue_light,
anki_vector.lights.green_light,
anki_vector.lights.red_light,
anki_vector.lights.white_light)
time.sleep(3)
cube.set_lights_off()
:param light1: The settings for the first light.
:param light2: The settings for the second light.
:param light3: The settings for the third light.
:param light4: The settings for the fourth light.
:param color_profile: The profile to be used for the cube lights
"""
params = lights.package_request_params((light1, light2, light3, light4), color_profile)
req = protocol.SetCubeLightsRequest(
object_id=self._object_id,
on_color=params['on_color'],
off_color=params['off_color'],
on_period_ms=params['on_period_ms'],
off_period_ms=params['off_period_ms'],
transition_on_period_ms=params['transition_on_period_ms'],
transition_off_period_ms=params['transition_off_period_ms'],
offset=[0, 0, 0, 0],
relative_to_x=0.0,
relative_to_y=0.0,
rotate=False,
make_relative=protocol.SetCubeLightsRequest.OFF) # pylint: disable=no-member
return await self.grpc_interface.SetCubeLights(req)
def set_lights(self, light: lights.Light, color_profile: lights.ColorProfile = lights.WHITE_BALANCED_CUBE_PROFILE):
"""Set all lights on the cube
.. testcode::
import anki_vector
import time
with anki_vector.Robot() as robot:
robot.world.connect_cube()
if robot.world.connected_light_cube:
cube = robot.world.connected_light_cube
# Set cube lights to yellow
cube.set_lights(anki_vector.lights.yellow_light)
time.sleep(3)
cube.set_lights_off()
:param light: The settings for the lights
:param color_profile: The profile to be used for the cube lights
"""
return self.set_light_corners(light, light, light, light, color_profile)
def set_lights_off(self, color_profile: lights.ColorProfile = lights.WHITE_BALANCED_CUBE_PROFILE):
"""Set all lights off on the cube
.. testcode::
import anki_vector
import time
with anki_vector.Robot() as robot:
robot.world.connect_cube()
if robot.world.connected_light_cube:
cube = robot.world.connected_light_cube
# Set cube lights to yellow
cube.set_lights(anki_vector.lights.yellow_light)
time.sleep(3)
# Turn off cube lights
cube.set_lights_off()
:param color_profile: The profile to be used for the cube lights
"""
return self.set_light_corners(lights.off_light, lights.off_light, lights.off_light, lights.off_light, color_profile)
#### Private Methods ####
def _repr_values(self):
return 'object_id=%s' % self.object_id
#### Properties ####
@property
def last_tapped_time(self) -> float:
"""The time the object was last tapped in SDK time.
.. testcode::
import time
import anki_vector
with anki_vector.Robot() as robot:
print("disconnecting from any connected cube...")
robot.world.disconnect_cube()
time.sleep(2)
print("connect to a cube...")
connectionResult = robot.world.connect_cube()
print("For the next 8 seconds, please tap and move the cube. Cube properties will be logged to console.")
for _ in range(16):
connected_cube = robot.world.connected_light_cube
if connected_cube:
print(f'last_tapped_time: {connected_cube.last_tapped_time}')
time.sleep(0.5)
"""
return self._last_tapped_time
@property
def last_tapped_robot_timestamp(self) -> float:
"""The time the object was last tapped in robot time.
.. testcode::
import time
import anki_vector
with anki_vector.Robot() as robot:
print("disconnecting from any connected cube...")
robot.world.disconnect_cube()
time.sleep(2)
print("connect to a cube...")
connectionResult = robot.world.connect_cube()
print("For the next 8 seconds, please tap and move the cube. Cube properties will be logged to console.")
for _ in range(16):
connected_cube = robot.world.connected_light_cube
if connected_cube:
print(f'last_tapped_robot_timestamp: {connected_cube.last_tapped_robot_timestamp}')
time.sleep(0.5)
"""
return self._last_tapped_robot_timestamp
@property
def last_moved_time(self) -> float:
"""The time the object was last moved in SDK time.
.. testcode::
import time
import anki_vector
with anki_vector.Robot() as robot:
print("disconnecting from any connected cube...")
robot.world.disconnect_cube()
time.sleep(2)
print("connect to a cube...")
connectionResult = robot.world.connect_cube()
print("For the next 8 seconds, please tap and move the cube. Cube properties will be logged to console.")
for _ in range(16):
connected_cube = robot.world.connected_light_cube
if connected_cube:
print(f'last_moved_time: {connected_cube.last_moved_time}')
time.sleep(0.5)
"""
return self._last_moved_time
@property
def last_moved_robot_timestamp(self) -> float:
"""The time the object was last moved in robot time.
.. testcode::
import time
import anki_vector
with anki_vector.Robot() as robot:
print("disconnecting from any connected cube...")
robot.world.disconnect_cube()
time.sleep(2)
print("connect to a cube...")
connectionResult = robot.world.connect_cube()
print("For the next 8 seconds, please tap and move the cube. Cube properties will be logged to console.")
for _ in range(16):
connected_cube = robot.world.connected_light_cube
if connected_cube:
print(f'last_moved_robot_timestamp: {connected_cube.last_moved_robot_timestamp}')
time.sleep(0.5)
"""
return self._last_moved_robot_timestamp
@property
def last_moved_start_time(self) -> float:
"""The time the object most recently started moving in SDK time.
.. testcode::
import time
import anki_vector
with anki_vector.Robot() as robot:
print("disconnecting from any connected cube...")
robot.world.disconnect_cube()
time.sleep(2)
print("connect to a cube...")
connectionResult = robot.world.connect_cube()
print("For the next 8 seconds, please tap and move the cube. Cube properties will be logged to console.")
for _ in range(16):
connected_cube = robot.world.connected_light_cube
if connected_cube:
print(f'last_moved_start_time: {connected_cube.last_moved_start_time}')
time.sleep(0.5)
"""
return self._last_moved_start_time
@property
def last_moved_start_robot_timestamp(self) -> float:
"""The time the object more recently started moving in robot time.
.. testcode::
import time
import anki_vector
with anki_vector.Robot() as robot:
print("disconnecting from any connected cube...")
robot.world.disconnect_cube()
time.sleep(2)
print("connect to a cube...")
connectionResult = robot.world.connect_cube()
print("For the next 8 seconds, please tap and move the cube. Cube properties will be logged to console.")
for _ in range(16):
connected_cube = robot.world.connected_light_cube
if connected_cube:
print(f'last_moved_start_robot_timestamp: {connected_cube.last_moved_start_robot_timestamp}')
time.sleep(0.5)
"""
return self._last_moved_start_robot_timestamp
@property
def last_up_axis_changed_time(self) -> float:
"""The time the object's orientation last changed in SDK time.
.. testcode::
import time
import anki_vector
with anki_vector.Robot() as robot:
print("disconnecting from any connected cube...")
robot.world.disconnect_cube()
time.sleep(2)
print("connect to a cube...")
connectionResult = robot.world.connect_cube()
print("For the next 8 seconds, please tap and move the cube. Cube properties will be logged to console.")
for _ in range(16):
connected_cube = robot.world.connected_light_cube
if connected_cube:
print(f'last_up_axis_changed_time: {connected_cube.last_up_axis_changed_time}')
time.sleep(0.5)
"""
return self._last_up_axis_changed_time
@property
def last_up_axis_changed_robot_timestamp(self) -> float:
"""Time the object's orientation last changed in robot time.
.. testcode::
import time
import anki_vector
with anki_vector.Robot() as robot:
print("disconnecting from any connected cube...")
robot.world.disconnect_cube()
time.sleep(2)
print("connect to a cube...")
connectionResult = robot.world.connect_cube()
print("For the next 8 seconds, please tap and move the cube. Cube properties will be logged to console.")
for _ in range(16):
connected_cube = robot.world.connected_light_cube
if connected_cube:
print(f'last_up_axis_changed_robot_timestamp: {connected_cube.last_up_axis_changed_robot_timestamp}')
time.sleep(0.5)
"""
return self._last_up_axis_changed_robot_timestamp
@property
def up_axis(self) -> protocol.UpAxis:
"""The object's up_axis value from the last time it changed.
.. testcode::
import time
import anki_vector
with anki_vector.Robot() as robot:
print("disconnecting from any connected cube...")
robot.world.disconnect_cube()
time.sleep(2)
print("connect to a cube...")
connectionResult = robot.world.connect_cube()
print("For the next 8 seconds, please tap and move the cube. Cube properties will be logged to console.")
for _ in range(16):
connected_cube = robot.world.connected_light_cube
if connected_cube:
print(f'up_axis: {connected_cube.up_axis}')
time.sleep(0.5)
"""
return self._up_axis
@property
def is_moving(self) -> bool:
"""True if the cube's accelerometer indicates that the cube is moving.
.. testcode::
import time
import anki_vector
with anki_vector.Robot() as robot:
print("disconnecting from any connected cube...")
robot.world.disconnect_cube()
time.sleep(2)
print("connect to a cube...")
connectionResult = robot.world.connect_cube()
print("For the next 8 seconds, please tap and move the cube. Cube properties will be logged to console.")
for _ in range(16):
connected_cube = robot.world.connected_light_cube
if connected_cube:
print(f'is_moving: {connected_cube.is_moving}')
time.sleep(0.5)
"""
return self._is_moving
@property
def is_connected(self) -> bool:
"""True if the cube is currently connected to the robot.
.. testcode::
import anki_vector
with anki_vector.Robot() as robot:
robot.world.connect_cube()
if robot.world.connected_light_cube:
cube = robot.world.connected_light_cube
print(f"{cube.is_connected}")
"""
return self._is_connected
@property
def top_face_orientation_rad(self) -> float:
"""Angular distance from the current reported up axis.
.. testcode::
import time
import anki_vector
with anki_vector.Robot() as robot:
print("disconnecting from any connected cube...")
robot.world.disconnect_cube()
time.sleep(2)
print("connect to a cube...")
connectionResult = robot.world.connect_cube()
print("For the next 8 seconds, please tap and move the cube. Cube properties will be logged to console.")
for _ in range(16):
connected_cube = robot.world.connected_light_cube
if connected_cube:
print(f'top_face_orientation_rad: {connected_cube.top_face_orientation_rad}')
time.sleep(0.5)
"""
return self._top_face_orientation_rad
@property
def factory_id(self) -> str:
"""The unique hardware id of the physical cube.
.. testcode::
import anki_vector
with anki_vector.Robot() as robot:
robot.world.connect_cube()
if robot.world.connected_light_cube:
cube = robot.world.connected_light_cube
print(f"{cube.factory_id}")
"""
return self._factory_id
@factory_id.setter
def factory_id(self, value: str):
self._factory_id = value
@property
def descriptive_name(self) -> str:
"""A descriptive name for this ObservableObject instance.
Note: Sub-classes should override this to add any other relevant info
for that object type.
.. testcode::
import anki_vector
with anki_vector.Robot() as robot:
robot.world.connect_cube()
if robot.world.connected_light_cube:
cube = robot.world.connected_light_cube
print(f"{cube.descriptive_name}")
"""
return "{0} id={1} factory_id={2} is_connected={3}".format(self.__class__.__name__, self._object_id, self._factory_id, self._is_connected)
@property
def object_id(self) -> int:
"""The internal ID assigned to the object.
This value can only be assigned once as it is static on the robot.
.. testcode::
import anki_vector
with anki_vector.Robot() as robot:
robot.world.connect_cube()
if robot.world.connected_light_cube:
cube = robot.world.connected_light_cube
print(f"{cube.object_id}")
"""
return self._object_id
@object_id.setter
def object_id(self, value: str):
if self._object_id is not None:
# We cannot currently rely on robot ensuring that object ID remains static
# E.g. in the case of a cube disconnecting and reconnecting it's removed
# and then re-added to blockworld which results in a new ID.
self.logger.warning("Changing object_id for %s from %s to %s", self.__class__, self._object_id, value)
else:
self.logger.debug("Setting object_id for %s to %s", self.__class__, value)
self._object_id = value
#### Private Event Handlers ####
def _on_object_connection_state_changed(self, _, msg):
if msg.object_type == LIGHT_CUBE_1_TYPE:
self._object_id = msg.object_id
if self._factory_id != msg.factory_id:
self.logger.debug('Factory id changed from {0} to {1}'.format(self._factory_id, msg.factory_id))
self._factory_id = msg.factory_id
if self._is_connected != msg.connected:
if msg.connected:
self.logger.debug('Object connected: %s', self)
else:
self.logger.debug('Object disconnected: %s', self)
self._is_connected = msg.connected
def _on_object_moved(self, _, msg):
if msg.object_id == self._object_id:
now = time.time()
started_moving = not self._is_moving
self._is_moving = True
self._last_event_time = now
self._last_moved_time = now
self._last_moved_robot_timestamp = msg.timestamp
if started_moving:
self._last_moved_start_time = now
self._last_moved_start_robot_timestamp = msg.timestamp
else:
self.logger.warning('An object not currently tracked by the world moved with id {0}'.format(msg.object_id))
async def _on_object_stopped_moving(self, _, msg):
if msg.object_id == self._object_id:
now = time.time()
self._last_event_time = now
move_duration = 0.0
# _is_moving might already be false.
# This happens for very short movements that are immediately
# considered stopped (no acceleration info is present)
if self._is_moving:
self._is_moving = False
move_duration = now - self._last_moved_start_time
await self._robot.events.dispatch_event(EvtObjectFinishedMove(self, move_duration), Events.object_finished_move)
else:
self.logger.warning('An object not currently tracked by the world stopped moving with id {0}'.format(msg.object_id))
def _on_object_up_axis_changed(self, _, msg):
if msg.object_id == self._object_id:
now = time.time()
self._up_axis = msg.up_axis
self._last_event_time = now
self._last_up_axis_changed_time = now
self._last_up_axis_changed_robot_timestamp = msg.timestamp
else:
self.logger.warning('Up Axis changed on an object not currently tracked by the world with id {0}'.format(msg.object_id))
def _on_object_tapped(self, _, msg):
if msg.object_id == self._object_id:
now = time.time()
self._last_event_time = now
self._last_tapped_time = now
self._last_tapped_robot_timestamp = msg.timestamp
else:
self.logger.warning('Tapped an object not currently tracked by the world with id {0}'.format(msg.object_id))
def _on_object_observed(self, _, msg):
if msg.object_id == self._object_id:
pose = util.Pose(x=msg.pose.x, y=msg.pose.y, z=msg.pose.z,
q0=msg.pose.q0, q1=msg.pose.q1,
q2=msg.pose.q2, q3=msg.pose.q3,
origin_id=msg.pose.origin_id)
image_rect = util.ImageRect(msg.img_rect.x_top_left,
msg.img_rect.y_top_left,
msg.img_rect.width,
msg.img_rect.height)
self._top_face_orientation_rad = msg.top_face_orientation_rad
self._on_observed(pose, image_rect, msg.timestamp)
def _on_object_connection_lost(self, _, msg):
if msg.object_id == self._object_id:
self._is_connected = False
class Charger(ObservableObject):
"""Vector's charger object, which the robot can observe and drive toward.
We get an :class:`anki_vector.objects.EvtObjectObserved` message when the