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
anki_vector/events.py ADDED
@@ -0,0 +1,420 @@
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
+ Event handler used to make functions subscribe to robot events.
17
+ """
18
+
19
+ __all__ = ['EventHandler', 'Events']
20
+
21
+ import asyncio
22
+ from concurrent.futures import CancelledError
23
+ from enum import Enum
24
+ import threading
25
+ from typing import Callable
26
+ import uuid
27
+
28
+ from .connection import Connection
29
+ from . import util
30
+ from .messaging import protocol
31
+
32
+
33
+ class Events(Enum):
34
+ """List of events available."""
35
+
36
+ # Robot
37
+ robot_state = "robot_state" #: Robot event containing changes to the robot's state.
38
+ mirror_mode_disabled = "mirror_mode_disabled" # : Robot event triggered when mirror mode (camera feed displayed on robot's face) is automatically disabled due to SDK no longer having control of the robot.
39
+ vision_modes_auto_disabled = "vision_modes_auto_disabled" # : Robot event triggered when all vision modes are automatically disabled due to the SDK no longer having control of the robot.
40
+ camera_settings_update = "camera_settings_update" # : Robot event triggered when camera exposure settings change
41
+
42
+ # Objects
43
+ object_available = "object_available" #: After the ConnectCube process is started, all available light cubes in range will broadcast an availability message through the Robot.
44
+ object_connection_state = "object_connection_state" # : Robot event for an object with the ability to connect to the robot digitally changing its connection state.
45
+ object_moved = "object_moved" #: Robot event triggered when an object starts moving.
46
+ object_stopped_moving = "object_stopped_moving" #: Robot event triggered when an object stops moving.
47
+ object_up_axis_changed = "object_up_axis_changed" #: Robot event triggered when an object's orientation changed.
48
+ object_tapped = "object_tapped" #: Robot event triggered when an object is tapped.
49
+ robot_observed_object = "robot_observed_object" #: Robot event triggered when an object is observed by the robot.
50
+ cube_connection_lost = "cube_connection_lost" #: Robot event triggered when an object's subscribed connection has been lost.
51
+
52
+ robot_observed_motion = "robot_observed_motion" #: Robot event dispatched when Vector observes motion.
53
+ robot_observed_face = "robot_observed_face" #: Robot event for when a face is observed by the robot.
54
+ robot_changed_observed_face_id = "robot_changed_observed_face_id" #: Robot event for when a known face changes its id.
55
+ robot_erased_enrolled_face = "robot_erased_enrolled_face" #: Robot event for when an enrolled face has been removed from the robot.
56
+ robot_renamed_enrolled_face = "robot_renamed_enrolled_face" #: Robot event for when a known face changes its name.
57
+ unexpected_movement = "unexpected_movement" #: Robot event for when it detects movement that does not match what motors were commanded (e.g. turning in the wrong direction)
58
+
59
+ wake_word = "wake_word" #: Robot event triggered when Vector hears "Hey Vector".
60
+ user_intent = "user_intent" #: Robot event triggered after Vector processes voice commands.
61
+
62
+ # Audio
63
+ audio_send_mode_changed = "audio_send_mode_changed" #: Robot event containing changes to the robot's audio stream source data processing mode.
64
+
65
+ # Generated by SDK
66
+ face_observed = "face_observed" #: Python event triggered in response to robot_observed_face with sdk metadata.
67
+ face_appeared = "face_appeared" #: Python event triggered when an face first receives robot_observed_face.
68
+ face_disappeared = "face_disappeared" #: Python event triggered when an face has not received a robot_observed_face for a specified time.
69
+ object_observed = "object_observed" #: Python event triggered in response to robot_observed_object with sdk metadata.
70
+ object_appeared = "object_appeared" #: Python event triggered when an object first receives robot_observed_object.
71
+ object_disappeared = "object_disappeared" #: Python event triggered when an object has not received a robot_observed_object for a specified time.
72
+ object_finished_move = "object_finished_move" #: Python event triggered in response to object_stopped_moving with duration data.
73
+ nav_map_update = "nav_map_update" #: Python event containing nav map data.
74
+ new_raw_camera_image = "new_raw_camera_image" #: Python event containing a raw camera image
75
+ new_camera_image = "new_camera_image" #: Python event containing a processed camera image (:class:`anki_vector.camera.CameraImage` instance)
76
+
77
+
78
+ class _EventCallback:
79
+ def __init__(self, callback, *args, _on_connection_thread: bool = False, **kwargs):
80
+ self._extra_args = args
81
+ self._extra_kwargs = kwargs
82
+ self._callback = callback
83
+ self._on_connection_thread = _on_connection_thread
84
+
85
+ @property
86
+ def on_connection_thread(self):
87
+ return self._on_connection_thread
88
+
89
+ @property
90
+ def callback(self):
91
+ return self._callback
92
+
93
+ @property
94
+ def extra_args(self):
95
+ return self._extra_args
96
+
97
+ @property
98
+ def extra_kwargs(self):
99
+ return self._extra_kwargs
100
+
101
+ def __eq__(self, other):
102
+ other_cb = other
103
+ if hasattr(other, "callback"):
104
+ other_cb = other.callback
105
+ return other_cb == self.callback
106
+
107
+ def __hash__(self):
108
+ return self._callback.__hash__()
109
+
110
+
111
+ class EventHandler:
112
+ """Listen for Vector events."""
113
+
114
+ def __init__(self, robot):
115
+ self.logger = util.get_class_logger(__name__, self)
116
+ self._robot = robot
117
+ self._conn = None
118
+ self._conn_id = None
119
+ self.listening_for_events = False
120
+ self.event_future = None
121
+ self._thread: threading.Thread = None
122
+ self._loop: asyncio.BaseEventLoop = None
123
+ self.subscribers = {}
124
+ self._done_signal: asyncio.Event = None
125
+
126
+ def start(self, connection: Connection):
127
+ """Start listening for events. Automatically called by the :class:`anki_vector.robot.Robot` class.
128
+
129
+ :param connection: A reference to the connection from the SDK to the robot.
130
+ :param loop: The loop to run the event task on.
131
+ """
132
+ self._conn = connection
133
+ self.listening_for_events = True
134
+ self._thread = threading.Thread(target=self._run_thread, daemon=True, name="Event Stream Handler Thread")
135
+ self._thread.start()
136
+
137
+ def _run_thread(self):
138
+ try:
139
+ self._loop = asyncio.new_event_loop()
140
+ asyncio.set_event_loop(self._loop)
141
+ self._done_signal = asyncio.Event()
142
+ # create an event stream handler on the connection thread
143
+ self.event_future = asyncio.run_coroutine_threadsafe(self._handle_event_stream(), self._conn.loop)
144
+
145
+ async def wait_until_done():
146
+ return await self._done_signal.wait()
147
+ self._loop.run_until_complete(wait_until_done())
148
+ finally:
149
+ self._loop.close()
150
+
151
+ def close(self):
152
+ """Stop listening for events. Automatically called by the :class:`anki_vector.robot.Robot` class.
153
+ """
154
+ self.listening_for_events = False
155
+ try:
156
+ self.event_future.cancel()
157
+ self.event_future.result()
158
+ except CancelledError:
159
+ pass
160
+ self._loop.call_soon_threadsafe(self._done_signal.set)
161
+ self._thread.join(timeout=5)
162
+ self._thread = None
163
+
164
+ def _notify(self, event_callback, event_name, event_data):
165
+ loop = self._loop
166
+ thread = self._thread
167
+ # For high priority events that shouldn't be blocked by user callbacks
168
+ # they will run directly on the connection thread. This should typically
169
+ # be used when setting robot properties from events.
170
+ if event_callback.on_connection_thread:
171
+ loop = self._conn.loop
172
+ thread = self._conn.thread
173
+
174
+ callback = event_callback.callback
175
+ args = event_callback.extra_args
176
+ kwargs = event_callback.extra_kwargs
177
+
178
+ if asyncio.iscoroutinefunction(callback):
179
+ callback = callback(self._robot, event_name, event_data, *args, **kwargs)
180
+ elif not asyncio.iscoroutine(callback):
181
+ async def call_async(fn, *args, **kwargs):
182
+ fn(*args, **kwargs)
183
+ callback = call_async(callback, self._robot, event_name, event_data, *args, **kwargs)
184
+
185
+ if threading.current_thread() is thread:
186
+ future = asyncio.ensure_future(callback, loop=loop)
187
+ else:
188
+ future = asyncio.run_coroutine_threadsafe(callback, loop=loop)
189
+ future.add_done_callback(self._done_callback)
190
+
191
+ def _done_callback(self, completed_future):
192
+ exc = completed_future.exception()
193
+ if exc:
194
+ self.logger.error("Event callback exception: %s", exc)
195
+ if isinstance(exc, TypeError) and "positional arguments but" in str(exc):
196
+ self.logger.error("The subscribed function may be missing parameters in its definition. Make sure it has robot, event_type and event positional parameters.")
197
+
198
+ async def dispatch_event_by_name(self, event_data, event_name: str):
199
+ """Dispatches event to event listeners by name.
200
+
201
+ .. testcode::
202
+
203
+ import anki_vector
204
+
205
+ def event_listener(robot, name, msg):
206
+ print(name) # will print 'my_event'
207
+ print(msg) # will print 'my_event dispatched'
208
+
209
+ with anki_vector.Robot() as robot:
210
+ robot.events.subscribe_by_name(event_listener, event_name='my_event')
211
+ robot.conn.run_coroutine(robot.events.dispatch_event_by_name('my_event dispatched', event_name='my_event'))
212
+
213
+ :param event_data: Data to accompany the event.
214
+ :param event_name: The name of the event that will result in func being called.
215
+ """
216
+ if not event_name:
217
+ self.logger.error('Bad event_name in dispatch_event.')
218
+
219
+ if event_name in self.subscribers.keys():
220
+ subscribers = self.subscribers[event_name].copy()
221
+ for callback in subscribers:
222
+ self._notify(callback, event_name, event_data)
223
+
224
+ async def dispatch_event(self, event_data, event_type: Events):
225
+ """Dispatches event to event listeners."""
226
+ if not event_type:
227
+ self.logger.error('Bad event_type in dispatch_event.')
228
+
229
+ event_name = event_type.value
230
+
231
+ await self.dispatch_event_by_name(event_data, event_name)
232
+
233
+ def _unpackage_event(self, enum_key: str, event):
234
+ event_key = event.WhichOneof(enum_key)
235
+ event_data = getattr(event, event_key)
236
+ if getattr(event_data, 'WhichOneof'):
237
+ # Object events are automatically unpackaged into their sub-event classes.
238
+ try:
239
+ return self._unpackage_event('object_event_type', event_data)
240
+ except ValueError:
241
+ pass
242
+ except TypeError:
243
+ pass
244
+
245
+ return event_key, event_data
246
+
247
+ async def _handle_event_stream(self):
248
+ self._conn_id = bytes(uuid.uuid4().hex, "utf-8")
249
+ try:
250
+ req = protocol.EventRequest(connection_id=self._conn_id)
251
+ async for evt in self._conn.grpc_interface.EventStream(req):
252
+ if not self.listening_for_events:
253
+ break
254
+ try:
255
+ unpackaged_event_key, unpackaged_event_data = self._unpackage_event('event_type', evt.event)
256
+ await self.dispatch_event_by_name(unpackaged_event_data, unpackaged_event_key)
257
+ except TypeError:
258
+ self.logger.warning('Unknown Event type')
259
+ except CancelledError:
260
+ self.logger.debug('Event handler task was cancelled. This is expected during disconnection.')
261
+
262
+ def subscribe_by_name(self, func: Callable, event_name: str, *args, **kwargs):
263
+ """Receive a method call when the specified event occurs.
264
+
265
+ .. testcode::
266
+
267
+ import anki_vector
268
+
269
+ def event_listener(robot, name, msg):
270
+ print(name) # will print 'my_event'
271
+ print(msg) # will print 'my_event dispatched'
272
+
273
+ with anki_vector.Robot() as robot:
274
+ robot.events.subscribe_by_name(event_listener, event_name='my_event')
275
+ robot.conn.run_coroutine(robot.events.dispatch_event_by_name('my_event dispatched', event_name='my_event'))
276
+
277
+ :param func: A method implemented in your code that will be called when the event is fired.
278
+ :param event_name: The name of the event that will result in func being called.
279
+ :param args: Additional positional arguments to this function will be passed through to the callback in the provided order.
280
+ :param kwargs: Additional keyword arguments to this function will be passed through to the callback.
281
+ """
282
+ if not event_name:
283
+ self.logger.error('Bad event_name in subscribe.')
284
+
285
+ if event_name not in self.subscribers.keys():
286
+ self.subscribers[event_name] = set()
287
+ self.subscribers[event_name].add(_EventCallback(func, *args, **kwargs))
288
+
289
+ def subscribe(self, func: Callable, event_type: Events, *args, **kwargs):
290
+ """Receive a method call when the specified event occurs.
291
+
292
+ .. testcode::
293
+
294
+ import anki_vector
295
+ from anki_vector.events import Events
296
+ from anki_vector.util import degrees
297
+ import threading
298
+
299
+ said_text = False
300
+
301
+ def on_robot_observed_face(robot, event_type, event, evt):
302
+ print("Vector sees a face")
303
+ global said_text
304
+ if not said_text:
305
+ said_text = True
306
+ robot.behavior.say_text("I see a face!")
307
+ evt.set()
308
+
309
+ with anki_vector.Robot(enable_face_detection=True) as robot:
310
+
311
+ # If necessary, move Vector's Head and Lift to make it easy to see his face
312
+ robot.behavior.set_head_angle(degrees(45.0))
313
+ robot.behavior.set_lift_height(0.0)
314
+
315
+ evt = threading.Event()
316
+ robot.events.subscribe(on_robot_observed_face, Events.robot_observed_face, evt)
317
+
318
+ print("------ waiting for face events, press ctrl+c to exit early ------")
319
+
320
+ try:
321
+ if not evt.wait(timeout=5):
322
+ print("------ Vector never saw your face! ------")
323
+ except KeyboardInterrupt:
324
+ pass
325
+
326
+ robot.events.unsubscribe(on_robot_observed_face, Events.robot_observed_face)
327
+
328
+ :param func: A method implemented in your code that will be called when the event is fired.
329
+ :param event_type: The enum type of the event that will result in func being called.
330
+ :param args: Additional positional arguments to this function will be passed through to the callback in the provided order.
331
+ :param kwargs: Additional keyword arguments to this function will be passed through to the callback.
332
+ """
333
+ if not event_type:
334
+ self.logger.error('Bad event_type in subscribe.')
335
+
336
+ event_name = event_type.value
337
+
338
+ self.subscribe_by_name(func, event_name, *args, **kwargs)
339
+
340
+ def unsubscribe_by_name(self, func: Callable, event_name: str):
341
+ """Unregister a previously subscribed method from an event.
342
+
343
+ .. testcode::
344
+
345
+ import anki_vector
346
+
347
+ def event_listener(name, msg):
348
+ print(name) # will print 'my_event'
349
+ print(msg) # will print 'my_event dispatched'
350
+
351
+ with anki_vector.Robot() as robot:
352
+ robot.events.subscribe_by_name(event_listener, event_name='my_event')
353
+ robot.conn.run_coroutine(robot.events.dispatch_event_by_name('my_event dispatched', event_name='my_event'))
354
+
355
+ :param func: The method you no longer wish to be called when an event fires.
356
+ :param event_name: The name of the event for which you no longer want to receive a method call.
357
+ """
358
+ if not event_name:
359
+ self.logger.error('Bad event_key in unsubscribe.')
360
+
361
+ if event_name in self.subscribers.keys():
362
+ event_subscribers = self.subscribers[event_name]
363
+ if func in event_subscribers:
364
+ event_subscribers.remove(func)
365
+ if not event_subscribers:
366
+ self.subscribers.pop(event_name, None)
367
+ else:
368
+ self.logger.error(f"The function '{func.__name__}' is not subscribed to '{event_name}'")
369
+ else:
370
+ self.logger.error(f"Cannot unsubscribe from event_type '{event_name}'. "
371
+ "It has no subscribers.")
372
+
373
+ def unsubscribe(self, func: Callable, event_type: Events):
374
+ """Unregister a previously subscribed method from an event.
375
+
376
+ .. testcode::
377
+
378
+ import anki_vector
379
+ from anki_vector.events import Events
380
+ from anki_vector.util import degrees
381
+ import threading
382
+
383
+ said_text = False
384
+
385
+ def on_robot_observed_face(robot, event_type, event, evt):
386
+ print("Vector sees a face")
387
+ global said_text
388
+ if not said_text:
389
+ said_text = True
390
+ robot.behavior.say_text("I see a face!")
391
+ evt.set()
392
+
393
+ with anki_vector.Robot(enable_face_detection=True) as robot:
394
+
395
+ # If necessary, move Vector's Head and Lift to make it easy to see his face
396
+ robot.behavior.set_head_angle(degrees(45.0))
397
+ robot.behavior.set_lift_height(0.0)
398
+
399
+ evt = threading.Event()
400
+ robot.events.subscribe(on_robot_observed_face, Events.robot_observed_face, evt)
401
+
402
+ print("------ waiting for face events, press ctrl+c to exit early ------")
403
+
404
+ try:
405
+ if not evt.wait(timeout=5):
406
+ print("------ Vector never saw your face! ------")
407
+ except KeyboardInterrupt:
408
+ pass
409
+
410
+ robot.events.unsubscribe(on_robot_observed_face, Events.robot_observed_face)
411
+
412
+ :param func: The enum type of the event you no longer wish to be called when an event fires.
413
+ :param event_type: The name of the event for which you no longer want to receive a method call.
414
+ """
415
+ if not event_type:
416
+ self.logger.error('Bad event_type in unsubscribe.')
417
+
418
+ event_name = event_type.value
419
+
420
+ self.unsubscribe_by_name(func, event_name)
@@ -0,0 +1,185 @@
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
+ SDK-specific exception classes for Vector.
17
+ """
18
+
19
+ from grpc import RpcError, StatusCode
20
+
21
+ from .messaging import protocol
22
+
23
+ # __all__ should order by constants, event classes, other classes, functions.
24
+ __all__ = ['VectorAsyncException',
25
+ 'VectorBehaviorControlException',
26
+ 'VectorCameraFeedException',
27
+ 'VectorCameraImageCaptureException',
28
+ 'VectorConfigurationException',
29
+ 'VectorConnectionException',
30
+ 'VectorControlException',
31
+ 'VectorControlTimeoutException',
32
+ 'VectorException',
33
+ 'VectorInvalidVersionException',
34
+ 'VectorNotFoundException',
35
+ 'VectorNotReadyException',
36
+ 'VectorPropertyValueNotReadyException',
37
+ 'VectorTimeoutException',
38
+ 'VectorUnauthenticatedException',
39
+ 'VectorUnavailableException',
40
+ 'VectorUnimplementedException',
41
+ 'VectorExternalAudioPlaybackException',
42
+ 'connection_error']
43
+
44
+
45
+ class VectorException(Exception):
46
+ """Base class of all Vector SDK exceptions."""
47
+
48
+
49
+ class VectorInvalidVersionException(VectorException):
50
+ """Your SDK version is not compatible with Vector's version."""
51
+
52
+ def __init__(self, version_response):
53
+ host = version_response.host_version
54
+ min_host = protocol.PROTOCOL_VERSION_MINIMUM
55
+ client = protocol.PROTOCOL_VERSION_CURRENT
56
+ if min_host > host:
57
+ error_message = (f"{self.__class__.__doc__}\n\n"
58
+ f"Your Vector is an older version that is not supported by the SDK: Vector={host}, SDK minimum={min_host}\n"
59
+ f"Use your app to make sure that Vector is on the internet, and able to download the latest update.")
60
+ else:
61
+ error_message = (f"{self.__class__.__doc__}\n\n"
62
+ f"Your SDK is an older version that is not supported by Vector: Vector={host}, SDK={client}\n"
63
+ f"Please install the latest SDK to continue.")
64
+ super().__init__(error_message)
65
+
66
+
67
+ class VectorControlException(VectorException):
68
+ """Unable to run a function which requires behavior control."""
69
+
70
+ def __init__(self, function):
71
+ msg = (f"Unable to run '{function}' because it requires behavior control.\n\n"
72
+ "Make sure to request control from Vector either by providing the 'behavior_control_level' parameter to Robot, "
73
+ "or directly call 'request_control()' on your connection.")
74
+ super().__init__(msg)
75
+
76
+
77
+ class VectorConnectionException(VectorException):
78
+ def __init__(self, cause):
79
+ doc_str = self.__class__.__doc__
80
+ if cause is not None:
81
+ self._status = cause.code()
82
+ self._details = cause.details()
83
+ msg = (f"{self._status}: {self._details}"
84
+ f"\n\n{doc_str if doc_str else 'Unknown error'}")
85
+ super().__init__(msg)
86
+ else:
87
+ super().__init__(doc_str)
88
+
89
+ @property
90
+ def status(self):
91
+ return self._status
92
+
93
+ @property
94
+ def details(self):
95
+ return self._details
96
+
97
+
98
+ class VectorUnauthenticatedException(VectorConnectionException):
99
+ """Failed to authenticate request."""
100
+
101
+
102
+ class VectorUnavailableException(VectorConnectionException):
103
+ """Unable to reach Vector."""
104
+
105
+
106
+ class VectorUnimplementedException(VectorConnectionException):
107
+ """Vector does not handle this message."""
108
+
109
+
110
+ class VectorTimeoutException(VectorConnectionException):
111
+ """Message took too long to complete."""
112
+
113
+
114
+ def connection_error(rpc_error: RpcError) -> VectorConnectionException:
115
+ """Translates grpc-specific errors to user-friendly :class:`VectorConnectionException`."""
116
+ code = rpc_error.code()
117
+ if code is StatusCode.UNAUTHENTICATED:
118
+ return VectorUnauthenticatedException(rpc_error)
119
+ if code is StatusCode.UNAVAILABLE:
120
+ return VectorUnavailableException(rpc_error)
121
+ if code is StatusCode.UNIMPLEMENTED:
122
+ return VectorUnimplementedException(rpc_error)
123
+ if code is StatusCode.DEADLINE_EXCEEDED:
124
+ return VectorTimeoutException(rpc_error)
125
+ return VectorConnectionException(rpc_error)
126
+
127
+
128
+ class _VectorGenericException(VectorException):
129
+ def __init__(self, _cause=None, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg
130
+ msg = (f"{self.__class__.__doc__}\n\n{_cause if _cause is not None else ''}")
131
+ super().__init__(msg.format(*args, **kwargs))
132
+
133
+
134
+ class VectorAsyncException(_VectorGenericException):
135
+ """Invalid asynchronous action attempted."""
136
+
137
+
138
+ class VectorBehaviorControlException(_VectorGenericException):
139
+ """Invalid behavior control action attempted."""
140
+
141
+
142
+ class VectorCameraFeedException(_VectorGenericException):
143
+ """The camera feed is not open.
144
+
145
+ Make sure to enable the camera feed either using Robot(show_viewer=True), or robot.camera.init_camera_feed()"""
146
+
147
+
148
+ class VectorCameraImageCaptureException(_VectorGenericException):
149
+ """Image capture exception."""
150
+
151
+
152
+ class VectorConfigurationException(_VectorGenericException):
153
+ """Invalid or missing configuration data."""
154
+
155
+
156
+ class VectorControlTimeoutException(_VectorGenericException):
157
+ """Failed to get control of Vector.
158
+
159
+ Please verify that Vector is connected to the internet, is on a flat surface, and is fully charged.
160
+ """
161
+
162
+
163
+ class VectorNotFoundException(_VectorGenericException):
164
+ """Unable to establish a connection to Vector.
165
+
166
+ Make sure you're on the same network, and Vector is connected to the internet.
167
+ """
168
+
169
+
170
+ class VectorNotReadyException(_VectorGenericException):
171
+ """Vector tried to do something before it was ready."""
172
+
173
+
174
+ class VectorPropertyValueNotReadyException(_VectorGenericException):
175
+ """Failed to retrieve the value for this property."""
176
+
177
+
178
+ class VectorUnreliableEventStreamException(VectorException):
179
+ """The robot event stream is currently unreliable.
180
+
181
+ Please ensure the app is not connected. If this persists, reboot Vector and try again."""
182
+
183
+
184
+ class VectorExternalAudioPlaybackException(VectorException):
185
+ """Failed to play external audio on Vector."""