/examples/tutorials/05_async_python/01_cube_blinker_sync.py

https://github.com/anki/cozmo-python-sdk · Python · 84 lines · 55 code · 2 blank · 27 comment · 3 complexity · 8889d1e42a0cab9f8c6b22ad28ae73ef MD5 · raw file

  1. #!/usr/bin/env python3
  2. # Copyright (c) 2016 Anki, Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License in the file LICENSE.txt or at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. '''Cube Blinker synchronous example
  16. Cozmo first looks around for a cube. Once a cube is found,
  17. the cube's lights blink green in a circular fashion. The
  18. script then waits for the cube to be tapped.
  19. '''
  20. import asyncio
  21. import sys
  22. import cozmo
  23. class BlinkyCube(cozmo.objects.LightCube):
  24. '''Subclass LightCube and add a light-chaser effect.'''
  25. def __init__(self, *a, **kw):
  26. super().__init__(*a, **kw)
  27. self._chaser = None
  28. def start_light_chaser(self):
  29. '''Cycles the lights around the cube with 1 corner lit up green,
  30. changing to the next corner every 0.1 seconds.
  31. '''
  32. if self._chaser:
  33. raise ValueError("Light chaser already running")
  34. async def _chaser():
  35. while True:
  36. for i in range(4):
  37. cols = [cozmo.lights.off_light] * 4
  38. cols[i] = cozmo.lights.green_light
  39. self.set_light_corners(*cols)
  40. await asyncio.sleep(0.1, loop=self._loop)
  41. self._chaser = asyncio.ensure_future(_chaser(), loop=self._loop)
  42. def stop_light_chaser(self):
  43. if self._chaser:
  44. self._chaser.cancel()
  45. self._chaser = None
  46. # Make sure World knows how to instantiate the subclass
  47. cozmo.world.World.light_cube_factory = BlinkyCube
  48. def cozmo_program(robot: cozmo.robot.Robot):
  49. cube = None
  50. look_around = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)
  51. try:
  52. cube = robot.world.wait_for_observed_light_cube(timeout=60)
  53. except asyncio.TimeoutError:
  54. print("Didn't find a cube :-(")
  55. return
  56. finally:
  57. look_around.stop()
  58. cube.start_light_chaser()
  59. try:
  60. print("Waiting for cube to be tapped")
  61. cube.wait_for_tap(timeout=10)
  62. print("Cube tapped")
  63. except asyncio.TimeoutError:
  64. print("No-one tapped our cube :-(")
  65. finally:
  66. cube.stop_light_chaser()
  67. cube.set_lights_off()
  68. cozmo.run_program(cozmo_program)