wirepod-vector-sdk-audio 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. anki_vector/__init__.py +43 -0
  2. anki_vector/animation.py +272 -0
  3. anki_vector/annotate.py +590 -0
  4. anki_vector/audio.py +212 -0
  5. anki_vector/audio_stream.py +335 -0
  6. anki_vector/behavior.py +1135 -0
  7. anki_vector/camera.py +670 -0
  8. anki_vector/camera_viewer/__init__.py +121 -0
  9. anki_vector/color.py +88 -0
  10. anki_vector/configure/__main__.py +331 -0
  11. anki_vector/connection.py +838 -0
  12. anki_vector/events.py +420 -0
  13. anki_vector/exceptions.py +185 -0
  14. anki_vector/faces.py +819 -0
  15. anki_vector/lights.py +210 -0
  16. anki_vector/mdns.py +131 -0
  17. anki_vector/messaging/__init__.py +45 -0
  18. anki_vector/messaging/alexa_pb2.py +36 -0
  19. anki_vector/messaging/alexa_pb2_grpc.py +3 -0
  20. anki_vector/messaging/behavior_pb2.py +40 -0
  21. anki_vector/messaging/behavior_pb2_grpc.py +3 -0
  22. anki_vector/messaging/client.py +33 -0
  23. anki_vector/messaging/cube_pb2.py +113 -0
  24. anki_vector/messaging/cube_pb2_grpc.py +3 -0
  25. anki_vector/messaging/extensions_pb2.py +25 -0
  26. anki_vector/messaging/extensions_pb2_grpc.py +3 -0
  27. anki_vector/messaging/external_interface_pb2.py +169 -0
  28. anki_vector/messaging/external_interface_pb2_grpc.py +1267 -0
  29. anki_vector/messaging/messages_pb2.py +431 -0
  30. anki_vector/messaging/messages_pb2_grpc.py +3 -0
  31. anki_vector/messaging/nav_map_pb2.py +33 -0
  32. anki_vector/messaging/nav_map_pb2_grpc.py +3 -0
  33. anki_vector/messaging/protocol.py +33 -0
  34. anki_vector/messaging/response_status_pb2.py +27 -0
  35. anki_vector/messaging/response_status_pb2_grpc.py +3 -0
  36. anki_vector/messaging/settings_pb2.py +72 -0
  37. anki_vector/messaging/settings_pb2_grpc.py +3 -0
  38. anki_vector/messaging/shared_pb2.py +54 -0
  39. anki_vector/messaging/shared_pb2_grpc.py +3 -0
  40. anki_vector/motors.py +127 -0
  41. anki_vector/nav_map.py +409 -0
  42. anki_vector/objects.py +1782 -0
  43. anki_vector/opengl/__init__.py +103 -0
  44. anki_vector/opengl/assets/LICENSE.txt +21 -0
  45. anki_vector/opengl/assets/cube.jpg +0 -0
  46. anki_vector/opengl/assets/cube.mtl +9 -0
  47. anki_vector/opengl/assets/cube.obj +1000 -0
  48. anki_vector/opengl/assets/vector.mtl +67 -0
  49. anki_vector/opengl/assets/vector.obj +13220 -0
  50. anki_vector/opengl/opengl.py +864 -0
  51. anki_vector/opengl/opengl_vector.py +620 -0
  52. anki_vector/opengl/opengl_viewer.py +689 -0
  53. anki_vector/photos.py +145 -0
  54. anki_vector/proximity.py +176 -0
  55. anki_vector/reserve_control/__main__.py +36 -0
  56. anki_vector/robot.py +930 -0
  57. anki_vector/screen.py +201 -0
  58. anki_vector/status.py +322 -0
  59. anki_vector/touch.py +119 -0
  60. anki_vector/user_intent.py +186 -0
  61. anki_vector/util.py +1132 -0
  62. anki_vector/version.py +15 -0
  63. anki_vector/viewer.py +403 -0
  64. anki_vector/vision.py +202 -0
  65. anki_vector/world.py +899 -0
  66. wirepod_vector_sdk_audio-0.9.0.dist-info/METADATA +80 -0
  67. wirepod_vector_sdk_audio-0.9.0.dist-info/RECORD +71 -0
  68. wirepod_vector_sdk_audio-0.9.0.dist-info/WHEEL +5 -0
  69. wirepod_vector_sdk_audio-0.9.0.dist-info/licenses/LICENSE.txt +180 -0
  70. wirepod_vector_sdk_audio-0.9.0.dist-info/top_level.txt +1 -0
  71. wirepod_vector_sdk_audio-0.9.0.dist-info/zip-safe +1 -0
@@ -0,0 +1,838 @@
1
+ # Copyright (c) 2018 Anki, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License in the file LICENSE.txt or at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Management of the connection to and from Vector.
17
+ """
18
+
19
+ # __all__ should order by constants, event classes, other classes, functions.
20
+ __all__ = ['ControlPriorityLevel', 'Connection', 'on_connection_thread']
21
+
22
+ import asyncio
23
+ from concurrent import futures
24
+ from enum import Enum
25
+ import functools
26
+ import inspect
27
+ import logging
28
+ import platform
29
+ import sys
30
+ import threading
31
+ from typing import Any, Awaitable, Callable, Coroutine, Dict, List
32
+
33
+ from google.protobuf.text_format import MessageToString
34
+ import grpc
35
+ import aiogrpc
36
+
37
+ from . import util
38
+ from .exceptions import (connection_error,
39
+ VectorAsyncException,
40
+ VectorBehaviorControlException,
41
+ VectorConfigurationException,
42
+ VectorControlException,
43
+ VectorControlTimeoutException,
44
+ VectorInvalidVersionException,
45
+ VectorNotFoundException)
46
+ from .messaging import client, protocol
47
+ from .version import __version__
48
+
49
+
50
+ class CancelType(Enum):
51
+ """Enum used to specify cancellation options for behaviors -- internal use only """
52
+ #: Cancellable as an 'Action'
53
+ CANCELLABLE_ACTION = 0
54
+ #: Cancellable as a 'Behavior'
55
+ CANCELLABLE_BEHAVIOR = 1
56
+
57
+
58
+ class ControlPriorityLevel(Enum):
59
+ """Enum used to specify the priority level for the program."""
60
+ #: Runs above mandatory physical reactions, will drive off table, perform while on a slope,
61
+ #: ignore low battery state, work in the dark, etc.
62
+ OVERRIDE_BEHAVIORS_PRIORITY = protocol.ControlRequest.OVERRIDE_BEHAVIORS # pylint: disable=no-member
63
+ #: Runs below Mandatory Physical Reactions such as tucking Vector's head and arms during a fall,
64
+ #: yet above Trigger-Word Detection. Default for normal operation.
65
+ DEFAULT_PRIORITY = protocol.ControlRequest.DEFAULT # pylint: disable=no-member
66
+ #: Holds control of robot before/after other SDK connections
67
+ #: Used to disable idle behaviors. Not to be used for regular behavior control.
68
+ RESERVE_CONTROL = protocol.ControlRequest.RESERVE_CONTROL # pylint: disable=no-member
69
+
70
+
71
+ class _ControlEventManager:
72
+ """This manages every :class:`asyncio.Event` that handles the behavior control
73
+ system.
74
+
75
+ These include three events: granted, lost, and request.
76
+
77
+ :class:`granted_event` represents the behavior system handing control to the SDK.
78
+
79
+ :class:`lost_event` represents a higher priority behavior taking control away from the SDK.
80
+
81
+ :class:`request_event` Is a way of alerting :class:`Connection` to request control.
82
+ """
83
+
84
+ def __init__(self, loop: asyncio.BaseEventLoop = None, priority: ControlPriorityLevel = None):
85
+ self._granted_event = asyncio.Event()
86
+ self._lost_event = asyncio.Event()
87
+ self._request_event = asyncio.Event()
88
+ self._has_control = False
89
+ self._priority = priority
90
+ self._is_shutdown = False
91
+
92
+ @property
93
+ def granted_event(self) -> asyncio.Event:
94
+ """This event is used to notify listeners that control has been granted to the SDK."""
95
+ return self._granted_event
96
+
97
+ @property
98
+ def lost_event(self) -> asyncio.Event:
99
+ """Represents a higher priority behavior taking control away from the SDK."""
100
+ return self._lost_event
101
+
102
+ @property
103
+ def request_event(self) -> asyncio.Event:
104
+ """Used to alert :class:`Connection` to request control."""
105
+ return self._request_event
106
+
107
+ @property
108
+ def has_control(self) -> bool:
109
+ """Check to see that the behavior system has control (without blocking by checking :class:`granted_event`)"""
110
+ return self._has_control
111
+
112
+ @property
113
+ def priority(self) -> ControlPriorityLevel:
114
+ """The currently desired priority for the SDK."""
115
+ return self._priority
116
+
117
+ @property
118
+ def is_shutdown(self) -> bool:
119
+ """Detect if the behavior control stream is supposed to shut down."""
120
+ return self._is_shutdown
121
+
122
+ def request(self, priority: ControlPriorityLevel = ControlPriorityLevel.DEFAULT_PRIORITY) -> None:
123
+ """Tell the behavior stream to request control via setting the :class:`request_event`.
124
+
125
+ This will signal Connection's :func:`_request_handler` generator to send a request control message on the BehaviorControl stream.
126
+ This signal happens asynchronously, and can be tracked using the :class:`granted_event` parameter.
127
+
128
+ :param priority: The level of control in the behavior system. This determines which actions are allowed to
129
+ interrupt the SDK execution. See :class:`ControlPriorityLevel` for more information.
130
+ """
131
+ if priority is None:
132
+ raise VectorBehaviorControlException("Must provide a priority level to request. To disable control, use {}.release().", self.__class__.__name__)
133
+ self._priority = priority
134
+ self._request_event.set()
135
+
136
+ def release(self) -> None:
137
+ """Tell the behavior stream to release control via setting the :class:`request_event` while priority is ``None``.
138
+
139
+ This will signal Connection's :func:`_request_handler` generator to send a release control message on the BehaviorControl stream.
140
+ This signal happens asynchronously, and can be tracked using the :class:`lost_event` parameter.
141
+ """
142
+ self._priority = None
143
+ self._request_event.set()
144
+
145
+ def update(self, enabled: bool) -> None:
146
+ """Update the current state of control (either enabled or disabled)
147
+
148
+ :param enabled: Used to enable/disable behavior control
149
+ """
150
+ self._has_control = enabled
151
+ if enabled:
152
+ self._granted_event.set()
153
+ self._lost_event.clear()
154
+ else:
155
+ self._lost_event.set()
156
+ self._granted_event.clear()
157
+
158
+ def shutdown(self) -> None:
159
+ """Tells the control stream to shut down.
160
+
161
+ This will return control to the rest of the behavior system.
162
+ """
163
+ self._has_control = False
164
+ self._granted_event.set()
165
+ self._lost_event.set()
166
+ self._is_shutdown = True
167
+ self._request_event.set()
168
+
169
+
170
+ class Connection:
171
+ """Creates and maintains a aiogrpc connection including managing the connection thread.
172
+ The connection thread decouples the actual messaging layer from the user's main thread,
173
+ and requires any network requests to be ran using :func:`asyncio.run_coroutine_threadsafe`
174
+ to make them run on the other thread. Connection provides two helper functions for running
175
+ a function on the connection thread: :func:`~Connection.run_coroutine` and
176
+ :func:`~Connection.run_soon`.
177
+
178
+ This class may be used to bypass the structures of the python sdk handled by
179
+ :class:`~anki_vector.robot.Robot`, and instead talk to aiogrpc more directly.
180
+
181
+ The values for the cert_file location and the guid can be found in your home directory in
182
+ the sdk_config.ini file.
183
+
184
+ .. code-block:: python
185
+
186
+ import anki_vector
187
+
188
+ # Connect to your Vector
189
+ conn = anki_vector.connection.Connection("Vector-XXXX", "XX.XX.XX.XX:443", "/path/to/file.cert", "<guid>")
190
+ conn.connect()
191
+ # Run your commands
192
+ async def play_animation():
193
+ # Run your commands
194
+ anim = anki_vector.messaging.protocol.Animation(name="anim_pounce_success_02")
195
+ anim_request = anki_vector.messaging.protocol.PlayAnimationRequest(animation=anim)
196
+ return await conn.grpc_interface.PlayAnimation(anim_request) # This needs to be run in an asyncio loop
197
+ conn.run_coroutine(play_animation()).result()
198
+ # Close the connection
199
+ conn.close()
200
+
201
+ :param name: Vector's name in the format of "Vector-XXXX".
202
+ :param host: The IP address and port of Vector in the format "XX.XX.XX.XX:443".
203
+ :param cert_file: The location of the certificate file on disk.
204
+ :param guid: Your robot's unique secret key.
205
+ :param behavior_control_level: pass one of :class:`ControlPriorityLevel` priority levels if the connection
206
+ requires behavior control, or None to decline control.
207
+ """
208
+
209
+ def __init__(self, name: str, host: str, cert_file: str, guid: str, behavior_control_level: ControlPriorityLevel = ControlPriorityLevel.DEFAULT_PRIORITY):
210
+ self._loop: asyncio.BaseEventLoop = None
211
+ self.name = name
212
+ self.host = host
213
+ self.cert_file = cert_file
214
+ self._interface = None
215
+ self._channel = None
216
+ self._has_control = False
217
+ self._logger = util.get_class_logger(__name__, self)
218
+ self._control_stream_task = None
219
+ self._control_events: _ControlEventManager = None
220
+ self._guid = guid
221
+ self._thread: threading.Thread = None
222
+ self._ready_signal: threading.Event = threading.Event()
223
+ self._done_signal: asyncio.Event = None
224
+ self._conn_exception = False
225
+ self._behavior_control_level = behavior_control_level
226
+ self.active_commands = []
227
+
228
+ @property
229
+ def loop(self) -> asyncio.BaseEventLoop:
230
+ """A direct reference to the loop on the connection thread.
231
+ Can be used to run functions in on thread.
232
+
233
+ .. testcode::
234
+
235
+ import anki_vector
236
+ import asyncio
237
+
238
+ async def connection_function():
239
+ print("I'm running in the connection thread event loop.")
240
+
241
+ with anki_vector.Robot() as robot:
242
+ asyncio.run_coroutine_threadsafe(connection_function(), robot.conn.loop)
243
+
244
+ :returns: The loop running inside the connection thread
245
+ """
246
+ if self._loop is None:
247
+ raise VectorAsyncException("Attempted to access the connection loop before it was ready")
248
+ return self._loop
249
+
250
+ @property
251
+ def thread(self) -> threading.Thread:
252
+ """A direct reference to the connection thread. Available to callers to determine if the
253
+ current thread is the connection thread.
254
+
255
+ .. testcode::
256
+
257
+ import anki_vector
258
+ import threading
259
+
260
+ with anki_vector.Robot() as robot:
261
+ if threading.current_thread() is robot.conn.thread:
262
+ print("This code is running on the connection thread")
263
+ else:
264
+ print("This code is not running on the connection thread")
265
+
266
+ :returns: The connection thread where all of the grpc messages are being processed.
267
+ """
268
+ if self._thread is None:
269
+ raise VectorAsyncException("Attempted to access the connection loop before it was ready")
270
+ return self._thread
271
+
272
+ @property
273
+ def grpc_interface(self) -> client.ExternalInterfaceStub:
274
+ """A direct reference to the connected aiogrpc interface.
275
+
276
+ This may be used to directly call grpc messages bypassing :class:`anki_vector.Robot`
277
+
278
+ .. code-block:: python
279
+
280
+ import anki_vector
281
+
282
+ # Connect to your Vector
283
+ conn = anki_vector.connection.Connection("Vector-XXXX", "XX.XX.XX.XX:443", "/path/to/file.cert", "<guid>")
284
+ conn.connect()
285
+ # Run your commands
286
+ async def play_animation():
287
+ # Run your commands
288
+ anim = anki_vector.messaging.protocol.Animation(name="anim_pounce_success_02")
289
+ anim_request = anki_vector.messaging.protocol.PlayAnimationRequest(animation=anim)
290
+ return await conn.grpc_interface.PlayAnimation(anim_request) # This needs to be run in an asyncio loop
291
+ conn.run_coroutine(play_animation()).result()
292
+ # Close the connection
293
+ conn.close()
294
+ """
295
+ return self._interface
296
+
297
+ @property
298
+ def behavior_control_level(self) -> ControlPriorityLevel:
299
+ """Returns the specific :class:`ControlPriorityLevel` requested for behavior control.
300
+
301
+ To be able to directly control Vector's motors, override his screen, play an animation, etc.,
302
+ the :class:`Connection` will need behavior control. This property identifies the enumerated
303
+ level of behavior control that the SDK will maintain over the robot.
304
+
305
+ For more information about behavior control, see :ref:`behavior <behavior>`.
306
+
307
+ .. code-block:: python
308
+
309
+ import anki_vector
310
+
311
+ with anki_vector.Robot() as robot:
312
+ print(robot.conn.behavior_control_level) # Will print ControlPriorityLevel.DEFAULT_PRIORITY
313
+ robot.conn.release_control()
314
+ print(robot.conn.behavior_control_level) # Will print None
315
+ """
316
+ return self._behavior_control_level
317
+
318
+ @property
319
+ def requires_behavior_control(self) -> bool:
320
+ """True if the :class:`Connection` requires behavior control.
321
+
322
+ To be able to directly control Vector's motors, override his screen, play an animation, etc.,
323
+ the :class:`Connection` will need behavior control. This boolean signifies that
324
+ the :class:`Connection` will try to maintain control of Vector's behavior system even after losing
325
+ control to higher priority robot behaviors such as returning home to charge a low battery.
326
+
327
+ For more information about behavior control, see :ref:`behavior <behavior>`.
328
+
329
+ .. code-block:: python
330
+
331
+ import time
332
+
333
+ import anki_vector
334
+
335
+ def callback(robot, event_type, event):
336
+ robot.conn.request_control()
337
+ print(robot.conn.requires_behavior_control) # Will print True
338
+ robot.anim.play_animation_trigger('GreetAfterLongTime')
339
+ robot.conn.release_control()
340
+
341
+ with anki_vector.Robot(behavior_control_level=None) as robot:
342
+ print(robot.conn.requires_behavior_control) # Will print False
343
+ robot.events.subscribe(callback, anki_vector.events.Events.robot_observed_face)
344
+
345
+ # Waits 10 seconds. Show Vector your face.
346
+ time.sleep(10)
347
+ """
348
+ return self._behavior_control_level is not None
349
+
350
+ @property
351
+ def control_lost_event(self) -> asyncio.Event:
352
+ """This provides an :class:`asyncio.Event` that a user may :func:`wait()` upon to
353
+ detect when Vector has taken control of the behavior system at a higher priority.
354
+
355
+ .. testcode::
356
+
357
+ import anki_vector
358
+
359
+ async def auto_reconnect(conn: anki_vector.connection.Connection):
360
+ await conn.control_lost_event.wait()
361
+ conn.request_control()
362
+ """
363
+ return self._control_events.lost_event
364
+
365
+ @property
366
+ def control_granted_event(self) -> asyncio.Event:
367
+ """This provides an :class:`asyncio.Event` that a user may :func:`wait()` upon to
368
+ detect when Vector has given control of the behavior system to the SDK program.
369
+
370
+ .. testcode::
371
+
372
+ import anki_vector
373
+
374
+ async def wait_for_control(conn: anki_vector.connection.Connection):
375
+ await conn.control_granted_event.wait()
376
+ # Run commands that require behavior control
377
+ """
378
+ return self._control_events.granted_event
379
+
380
+ def request_control(self, behavior_control_level: ControlPriorityLevel = ControlPriorityLevel.DEFAULT_PRIORITY, timeout: float = 10.0):
381
+ """Explicitly request behavior control. Typically used after detecting :func:`control_lost_event`.
382
+
383
+ To be able to directly control Vector's motors, override his screen, play an animation, etc.,
384
+ the :class:`Connection` will need behavior control. This function will acquire control
385
+ of Vector's behavior system. This will raise a :class:`VectorControlTimeoutException` if it fails
386
+ to gain control before the timeout.
387
+
388
+ For more information about behavior control, see :ref:`behavior <behavior>`
389
+
390
+ .. testcode::
391
+
392
+ import anki_vector
393
+
394
+ async def auto_reconnect(conn: anki_vector.connection.Connection):
395
+ await conn.control_lost_event.wait()
396
+ conn.request_control(timeout=5.0)
397
+
398
+ :param timeout: The time allotted to attempt a connection, in seconds.
399
+ :param behavior_control_level: request control of Vector's behavior system at a specific level of control.
400
+ See :class:`ControlPriorityLevel` for more information.
401
+ """
402
+ if not isinstance(behavior_control_level, ControlPriorityLevel):
403
+ raise TypeError("behavior_control_level must be of type ControlPriorityLevel")
404
+ if self._thread is threading.current_thread():
405
+ return asyncio.ensure_future(self._request_control(behavior_control_level=behavior_control_level, timeout=timeout), loop=self._loop)
406
+ return self.run_coroutine(self._request_control(behavior_control_level=behavior_control_level, timeout=timeout))
407
+
408
+ async def _request_control(self, behavior_control_level: ControlPriorityLevel = ControlPriorityLevel.DEFAULT_PRIORITY, timeout: float = 10.0):
409
+ self._behavior_control_level = behavior_control_level
410
+ self._control_events.request(self._behavior_control_level)
411
+ try:
412
+ self._has_control = await asyncio.wait_for(self.control_granted_event.wait(), timeout)
413
+ except futures.TimeoutError as e:
414
+ raise VectorControlTimeoutException(f"Surpassed timeout of {timeout}s") from e
415
+
416
+ def release_control(self, timeout: float = 10.0):
417
+ """Explicitly release control. Typically used after detecting :func:`control_lost_event`.
418
+
419
+ To be able to directly control Vector's motors, override his screen, play an animation, etc.,
420
+ the :class:`Connection` will need behavior control. This function will release control
421
+ of Vector's behavior system. This will raise a :class:`VectorControlTimeoutException` if it fails
422
+ to receive a control_lost event before the timeout.
423
+
424
+ .. testcode::
425
+
426
+ import anki_vector
427
+
428
+ async def wait_for_control(conn: anki_vector.connection.Connection):
429
+ await conn.control_granted_event.wait()
430
+ # Run commands that require behavior control
431
+ conn.release_control()
432
+
433
+ :param timeout: The time allotted to attempt to release control, in seconds.
434
+ """
435
+ if self._thread is threading.current_thread():
436
+ return asyncio.ensure_future(self._release_control(timeout=timeout), loop=self._loop)
437
+ return self.run_coroutine(self._release_control(timeout=timeout))
438
+
439
+ async def _release_control(self, timeout: float = 10.0):
440
+ self._behavior_control_level = None
441
+ self._control_events.release()
442
+ try:
443
+ self._has_control = await asyncio.wait_for(self.control_lost_event.wait(), timeout)
444
+ except futures.TimeoutError as e:
445
+ raise VectorControlTimeoutException(f"Surpassed timeout of {timeout}s") from e
446
+
447
+ def connect(self, timeout: float = 10.0) -> None:
448
+ """Connect to Vector. This will start the connection thread which handles all messages
449
+ between Vector and Python.
450
+
451
+ .. code-block:: python
452
+
453
+ import anki_vector
454
+
455
+ # Connect to your Vector
456
+ conn = anki_vector.connection.Connection("Vector-XXXX", "XX.XX.XX.XX:443", "/path/to/file.cert", "<guid>")
457
+ conn.connect()
458
+ # Run your commands
459
+ async def play_animation():
460
+ # Run your commands
461
+ anim = anki_vector.messaging.protocol.Animation(name="anim_pounce_success_02")
462
+ anim_request = anki_vector.messaging.protocol.PlayAnimationRequest(animation=anim)
463
+ return await conn.grpc_interface.PlayAnimation(anim_request) # This needs to be run in an asyncio loop
464
+ conn.run_coroutine(play_animation()).result()
465
+ # Close the connection
466
+ conn.close()
467
+
468
+ :param timeout: The time allotted to attempt a connection, in seconds.
469
+ """
470
+ if self._thread:
471
+ raise VectorAsyncException("\n\nRepeated connections made to open Connection.")
472
+ self._ready_signal.clear()
473
+ self._thread = threading.Thread(target=self._connect, args=(timeout,), daemon=True, name="gRPC Connection Handler Thread")
474
+ self._thread.start()
475
+ ready = self._ready_signal.wait(timeout=4 * timeout)
476
+ if not ready:
477
+ raise VectorNotFoundException()
478
+ if hasattr(self._ready_signal, "exception"):
479
+ e = getattr(self._ready_signal, "exception")
480
+ delattr(self._ready_signal, "exception")
481
+ raise e
482
+
483
+ def _connect(self, timeout: float) -> None:
484
+ """The function that runs on the connection thread. This will connect to Vector,
485
+ and establish the BehaviorControl stream.
486
+ """
487
+ try:
488
+ if threading.main_thread() is threading.current_thread():
489
+ raise VectorAsyncException("\n\nConnection._connect must be run outside of the main thread.")
490
+ self._loop = asyncio.new_event_loop()
491
+ asyncio.set_event_loop(self._loop)
492
+ self._done_signal = asyncio.Event()
493
+ if not self._behavior_control_level:
494
+ self._control_events = _ControlEventManager(self._loop)
495
+ else:
496
+ self._control_events = _ControlEventManager(self._loop, priority=self._behavior_control_level)
497
+
498
+ trusted_certs = None
499
+ if not self.cert_file is None:
500
+ with open(self.cert_file, 'rb') as cert:
501
+ trusted_certs = cert.read()
502
+ else:
503
+ raise VectorConfigurationException("Must provide a cert file to authenticate to Vector.")
504
+
505
+
506
+ # Pin the robot certificate for opening the channel
507
+ channel_credentials = aiogrpc.ssl_channel_credentials(root_certificates=trusted_certs)
508
+ # Add authorization header for all the calls
509
+ call_credentials = aiogrpc.access_token_call_credentials(self._guid)
510
+
511
+ credentials = aiogrpc.composite_channel_credentials(channel_credentials, call_credentials)
512
+
513
+ self._logger.info(f"Connecting to {self.host} for {self.name} using {self.cert_file}")
514
+ self._channel = aiogrpc.secure_channel(self.host, credentials,
515
+ options=(("grpc.ssl_target_name_override", self.name,),))
516
+
517
+ # Verify the connection to Vector is able to be established (client-side)
518
+ try:
519
+ # Explicitly grab _channel._channel to test the underlying grpc channel directly
520
+ grpc.channel_ready_future(self._channel._channel).result(timeout=timeout) # pylint: disable=protected-access
521
+ except grpc.FutureTimeoutError as e:
522
+ raise VectorNotFoundException() from e
523
+
524
+ self._interface = client.ExternalInterfaceStub(self._channel)
525
+
526
+ # Verify Vector and the SDK have compatible protocol versions
527
+ version = protocol.ProtocolVersionRequest(client_version=protocol.PROTOCOL_VERSION_CURRENT, min_host_version=protocol.PROTOCOL_VERSION_MINIMUM)
528
+ protocol_version = self._loop.run_until_complete(self._interface.ProtocolVersion(version))
529
+ if protocol_version.result != protocol.ProtocolVersionResponse.SUCCESS or protocol.PROTOCOL_VERSION_MINIMUM > protocol_version.host_version: # pylint: disable=no-member
530
+ raise VectorInvalidVersionException(protocol_version)
531
+
532
+ self._control_stream_task = self._loop.create_task(self._open_connections())
533
+
534
+ # Initialze SDK
535
+ sdk_module_version = __version__
536
+ python_version = platform.python_version()
537
+ python_implementation = platform.python_implementation()
538
+ os_version = platform.platform()
539
+ cpu_version = platform.machine()
540
+ initialize = protocol.SDKInitializationRequest(sdk_module_version=sdk_module_version,
541
+ python_version=python_version,
542
+ python_implementation=python_implementation,
543
+ os_version=os_version,
544
+ cpu_version=cpu_version)
545
+ self._loop.run_until_complete(self._interface.SDKInitialization(initialize))
546
+
547
+ if self._behavior_control_level:
548
+ self._loop.run_until_complete(self._request_control(behavior_control_level=self._behavior_control_level, timeout=timeout))
549
+ except grpc.RpcError as rpc_error: # pylint: disable=broad-except
550
+ setattr(self._ready_signal, "exception", connection_error(rpc_error))
551
+ self._loop.close()
552
+ return
553
+ except Exception as e: # pylint: disable=broad-except
554
+ # Propagate the errors to the calling thread
555
+ setattr(self._ready_signal, "exception", e)
556
+ self._loop.close()
557
+ return
558
+ finally:
559
+ self._ready_signal.set()
560
+
561
+ try:
562
+ async def wait_until_done():
563
+ return await self._done_signal.wait()
564
+ self._loop.run_until_complete(wait_until_done())
565
+ finally:
566
+ self._loop.close()
567
+
568
+ async def _request_handler(self):
569
+ """Handles generating messages for the BehaviorControl stream."""
570
+ while await self._control_events.request_event.wait():
571
+ self._control_events.request_event.clear()
572
+ if self._control_events.is_shutdown:
573
+ return
574
+ priority = self._control_events.priority
575
+ if priority is None:
576
+ msg = protocol.ControlRelease()
577
+ msg = protocol.BehaviorControlRequest(control_release=msg)
578
+ else:
579
+ msg = protocol.ControlRequest(priority=priority.value)
580
+ msg = protocol.BehaviorControlRequest(control_request=msg)
581
+ self._logger.debug(f"BehaviorControl {MessageToString(msg, as_one_line=True)}")
582
+ yield msg
583
+
584
+ async def _open_connections(self):
585
+ """Starts the BehaviorControl stream, and handles the messages coming back from the robot."""
586
+ try:
587
+ async for response in self._interface.BehaviorControl(self._request_handler()):
588
+ response_type = response.WhichOneof("response_type")
589
+ if response_type == 'control_granted_response':
590
+ self._logger.info(f"BehaviorControl {MessageToString(response, as_one_line=True)}")
591
+ self._control_events.update(True)
592
+ elif response_type == 'control_lost_event':
593
+ self._cancel_active()
594
+ self._logger.info(f"BehaviorControl {MessageToString(response, as_one_line=True)}")
595
+ self._control_events.update(False)
596
+ except futures.CancelledError:
597
+ self._logger.debug('Behavior handler task was cancelled. This is expected during disconnection.')
598
+
599
+ def _cancel_active(self):
600
+ for fut in self.active_commands:
601
+ if not fut.done():
602
+ fut.cancel()
603
+ self.active_commands = []
604
+
605
+ def close(self):
606
+ """Cleanup the connection, and shutdown all the event handlers.
607
+
608
+ Usually this should be invoked by the Robot class when it closes.
609
+
610
+ .. code-block:: python
611
+
612
+ import anki_vector
613
+
614
+ # Connect to your Vector
615
+ conn = anki_vector.connection.Connection("Vector-XXXX", "XX.XX.XX.XX:443", "/path/to/file.cert", "<guid>")
616
+ conn.connect()
617
+ # Run your commands
618
+ async def play_animation():
619
+ # Run your commands
620
+ anim = anki_vector.messaging.protocol.Animation(name="anim_pounce_success_02")
621
+ anim_request = anki_vector.messaging.protocol.PlayAnimationRequest(animation=anim)
622
+ return await conn.grpc_interface.PlayAnimation(anim_request) # This needs to be run in an asyncio loop
623
+ conn.run_coroutine(play_animation()).result()
624
+ # Close the connection
625
+ conn.close()
626
+ """
627
+ try:
628
+ if self._control_events:
629
+ self._control_events.shutdown()
630
+ if self._control_stream_task:
631
+ self._control_stream_task.cancel()
632
+ self.run_coroutine(self._control_stream_task).result()
633
+ self._cancel_active()
634
+ if self._channel:
635
+ self.run_coroutine(self._channel.close()).result()
636
+ self.run_coroutine(self._done_signal.set)
637
+ self._thread.join(timeout=5)
638
+ except:
639
+ pass
640
+ finally:
641
+ self._thread = None
642
+
643
+ def run_soon(self, coro: Awaitable) -> None:
644
+ """Schedules the given awaitable to run on the event loop for the connection thread.
645
+
646
+ .. testcode::
647
+
648
+ import anki_vector
649
+ import time
650
+
651
+ async def my_coroutine():
652
+ print("Running on the connection thread")
653
+
654
+ with anki_vector.Robot() as robot:
655
+ robot.conn.run_soon(my_coroutine())
656
+ time.sleep(1)
657
+
658
+ :param coro: The coroutine, task or any awaitable to schedule for execution on the connection thread.
659
+ """
660
+ if coro is None or not inspect.isawaitable(coro):
661
+ raise VectorAsyncException(f"\n\n{coro.__name__ if hasattr(coro, '__name__') else coro} is not awaitable, so cannot be ran with run_soon.\n")
662
+
663
+ def soon():
664
+ try:
665
+ asyncio.ensure_future(coro)
666
+ except TypeError as e:
667
+ raise VectorAsyncException(f"\n\n{coro.__name__ if hasattr(coro, '__name__') else coro} could not be ensured as a future.\n") from e
668
+ if threading.current_thread() is self._thread:
669
+ self._loop.call_soon(soon)
670
+ else:
671
+ self._loop.call_soon_threadsafe(soon)
672
+
673
+ def run_coroutine(self, coro: Awaitable) -> Any:
674
+ """Runs a given awaitable on the connection thread's event loop.
675
+ Cannot be called from within the connection thread.
676
+
677
+ .. testcode::
678
+
679
+ import anki_vector
680
+
681
+ async def my_coroutine():
682
+ print("Running on the connection thread")
683
+ return "Finished"
684
+
685
+ with anki_vector.Robot() as robot:
686
+ result = robot.conn.run_coroutine(my_coroutine())
687
+
688
+ :param coro: The coroutine, task or any other awaitable which should be executed.
689
+ :returns: The result of the awaitable's execution.
690
+ """
691
+ if threading.current_thread() is self._thread:
692
+ raise VectorAsyncException("Attempting to invoke async from same thread."
693
+ "Instead you may want to use 'run_soon'")
694
+ if asyncio.iscoroutinefunction(coro) or asyncio.iscoroutine(coro):
695
+ return self._run_coroutine(coro)
696
+ if asyncio.isfuture(coro):
697
+ async def future_coro():
698
+ return await coro
699
+ return self._run_coroutine(future_coro())
700
+ if callable(coro):
701
+ async def wrapped_coro():
702
+ return coro()
703
+ return self._run_coroutine(wrapped_coro())
704
+ raise VectorAsyncException("\n\nInvalid parameter to run_coroutine: {}\n"
705
+ "This function expects a coroutine, task, or awaitable.".format(type(coro)))
706
+
707
+ def _run_coroutine(self, coro):
708
+ return asyncio.run_coroutine_threadsafe(coro, self._loop)
709
+
710
+
711
+ def on_connection_thread(log_messaging: bool = True, requires_control: bool = True, is_cancellable: CancelType = None) -> Callable[[Coroutine[util.Component, Any, None]], Any]:
712
+ """A decorator generator used internally to denote which functions will run on
713
+ the connection thread. This unblocks the caller of the wrapped function
714
+ and allows them to continue running while the messages are being processed.
715
+
716
+ .. code-block:: python
717
+
718
+ import anki_vector
719
+
720
+ class MyComponent(anki_vector.util.Component):
721
+ @connection._on_connection_thread()
722
+ async def on_connection_thread(self):
723
+ # Do work on the connection thread
724
+
725
+ :param log_messaging: True if the log output should include the entire message or just the size. Recommended for
726
+ large binary return values.
727
+ :param requires_control: True if the function should wait until behavior control is granted before executing.
728
+ :param is_cancellable: use a valid enum of :class:`CancelType` to specify the type of cancellation for the
729
+ function. Defaults to 'None' implying no support for responding to cancellation.
730
+ :returns: A decorator which has 3 possible returns based on context: the result of the decorated function,
731
+ the :class:`concurrent.futures.Future` which points to the decorated function, or the
732
+ :class:`asyncio.Future` which points to the decorated function.
733
+ These contexts are: when the robot is a :class:`~anki_vector.robot.Robot`,
734
+ when the robot is an :class:`~anki_vector.robot.AsyncRobot`, and when
735
+ called from the connection thread respectively.
736
+ """
737
+ def _on_connection_thread_decorator(func: Coroutine) -> Any:
738
+ """A decorator which specifies a function to be executed on the connection thread
739
+
740
+ :params func: The function to be decorated
741
+ :returns: There are 3 possible returns based on context: the result of the decorated function,
742
+ the :class:`concurrent.futures.Future` which points to the decorated function, or the
743
+ :class:`asyncio.Future` which points to the decorated function.
744
+ These contexts are: when the robot is a :class:`anki_vector.robot.Robot`,
745
+ when the robot is an :class:`anki_vector.robot.AsyncRobot`, and when
746
+ called from the connection thread respectively.
747
+ """
748
+ if not asyncio.iscoroutinefunction(func):
749
+ raise VectorAsyncException("\n\nCannot define non-coroutine function '{}' to run on connection thread.\n"
750
+ "Make sure the function is defined using 'async def'.".format(func.__name__ if hasattr(func, "__name__") else func))
751
+
752
+ @functools.wraps(func)
753
+ async def log_handler(conn: Connection, func: Coroutine, logger: logging.Logger, *args: List[Any], **kwargs: Dict[str, Any]) -> Coroutine:
754
+ """Wrap the provided coroutine to better express exceptions as specific :class:`anki_vector.exceptions.VectorException`s, and
755
+ adds logging to incoming (from the robot) and outgoing (to the robot) messages.
756
+ """
757
+ result = None
758
+ # TODO: only have the request wait for control if we're not done. If done raise an exception.
759
+ control = conn.control_granted_event
760
+ if requires_control and not control.is_set():
761
+ if not conn.requires_behavior_control:
762
+ raise VectorControlException(func.__name__)
763
+ logger.info(f"Delaying {func.__name__} until behavior control is granted")
764
+ await asyncio.wait([asyncio.create_task(conn.control_granted_event.wait())], timeout=10)
765
+ message = args[1:]
766
+ outgoing = message if log_messaging else "size = {} bytes".format(sys.getsizeof(message))
767
+ logger.debug(f'Outgoing {func.__name__}: {outgoing}')
768
+ try:
769
+ result = await func(*args, **kwargs)
770
+ except grpc.RpcError as rpc_error:
771
+ raise connection_error(rpc_error) from rpc_error
772
+ incoming = str(result).strip() if log_messaging else "size = {} bytes".format(sys.getsizeof(result))
773
+ logger.debug(f'Incoming {func.__name__}: {type(result).__name__} {incoming}')
774
+ return result
775
+
776
+ @functools.wraps(func)
777
+ def result(*args: List[Any], **kwargs: Dict[str, Any]) -> Any:
778
+ """The function that is the result of the decorator. Provides a wrapped function.
779
+
780
+ :param _return_future: A hidden parameter which allows the wrapped function to explicitly
781
+ return a future (default for AsyncRobot) or not (default for Robot).
782
+ :returns: Based on context this can return the result of the decorated function,
783
+ the :class:`concurrent.futures.Future` which points to the decorated function, or the
784
+ :class:`asyncio.Future` which points to the decorated function.
785
+ These contexts are: when the robot is a :class:`anki_vector.robot.Robot`,
786
+ when the robot is an :class:`anki_vector.robot.AsyncRobot`, and when
787
+ called from the connection thread respectively."""
788
+ self = args[0] # Get the self reference from the function call
789
+ # if the call supplies a _return_future parameter then override force_async with that.
790
+ _return_future = kwargs.pop('_return_future', self.force_async)
791
+
792
+ action_id = None
793
+ if is_cancellable == CancelType.CANCELLABLE_ACTION:
794
+ action_id = self._get_next_action_id()
795
+ kwargs['_action_id'] = action_id
796
+
797
+ wrapped_coroutine = log_handler(self.conn, func, self.logger, *args, **kwargs)
798
+
799
+ if threading.current_thread() == self.conn.thread:
800
+ if self.conn.loop.is_running():
801
+ return asyncio.ensure_future(wrapped_coroutine, loop=self.conn.loop)
802
+ raise VectorAsyncException("\n\nThe connection thread loop is not running, but a "
803
+ "function '{}' is being invoked on that thread.\n".format(func.__name__ if hasattr(func, "__name__") else func))
804
+ future = asyncio.run_coroutine_threadsafe(wrapped_coroutine, self.conn.loop)
805
+
806
+ if is_cancellable == CancelType.CANCELLABLE_ACTION:
807
+ def user_cancelled_action(fut):
808
+ if action_id is None:
809
+ return
810
+
811
+ if fut.cancelled():
812
+ self._abort_action(action_id)
813
+
814
+ future.add_done_callback(user_cancelled_action)
815
+
816
+ if is_cancellable == CancelType.CANCELLABLE_BEHAVIOR:
817
+ def user_cancelled_behavior(fut):
818
+ if fut.cancelled():
819
+ self._abort_behavior()
820
+
821
+ future.add_done_callback(user_cancelled_behavior)
822
+
823
+ if requires_control:
824
+ self.conn.active_commands.append(future)
825
+
826
+ def clear_when_done(fut):
827
+ if fut in self.conn.active_commands:
828
+ self.conn.active_commands.remove(fut)
829
+ future.add_done_callback(clear_when_done)
830
+ if _return_future:
831
+ return future
832
+ try:
833
+ return future.result()
834
+ except futures.CancelledError:
835
+ self.logger.warning(f"{func.__name__} cancelled because behavior control was lost")
836
+ return None
837
+ return result
838
+ return _on_connection_thread_decorator