Cozmo人工智能机器人SDK使用笔记(5)-时序部分async_sync

举报
zhangrelay 发表于 2021/07/15 03:13:32 2021/07/15
【摘要】 Cozmo首先寻找一个立方体。 找到立方体后,立方体的灯以循环方式绿色闪烁,然后等待轻敲立方体。 此时,程序分别为同步和异步两种类型,注意区分。 1. 同步 立方体闪烁同步示例 import asyncioimport sys import cozmo class BlinkyCube(cozmo.objects.LightCube): '''Subclass Li...

Cozmo首先寻找一个立方体。 找到立方体后,立方体的灯以循环方式绿色闪烁,然后等待轻敲立方体。

此时,程序分别为同步和异步两种类型,注意区分。


1. 同步

立方体闪烁同步示例


  
  1. import asyncio
  2. import sys
  3. import cozmo
  4. class BlinkyCube(cozmo.objects.LightCube):
  5. '''Subclass LightCube and add a light-chaser effect.'''
  6. def __init__(self, *a, **kw):
  7. super().__init__(*a, **kw)
  8. self._chaser = None
  9. def start_light_chaser(self):
  10. '''Cycles the lights around the cube with 1 corner lit up green,
  11. changing to the next corner every 0.1 seconds.
  12. '''
  13. if self._chaser:
  14. raise ValueError("Light chaser already running")
  15. async def _chaser():
  16. while True:
  17. for i in range(4):
  18. cols = [cozmo.lights.off_light] * 4
  19. cols[i] = cozmo.lights.green_light
  20. self.set_light_corners(*cols)
  21. await asyncio.sleep(0.1, loop=self._loop)
  22. self._chaser = asyncio.ensure_future(_chaser(), loop=self._loop)
  23. def stop_light_chaser(self):
  24. if self._chaser:
  25. self._chaser.cancel()
  26. self._chaser = None
  27. # Make sure World knows how to instantiate the subclass
  28. cozmo.world.World.light_cube_factory = BlinkyCube
  29. def cozmo_program(robot: cozmo.robot.Robot):
  30. cube = None
  31. look_around = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)
  32. try:
  33. cube = robot.world.wait_for_observed_light_cube(timeout=60)
  34. except asyncio.TimeoutError:
  35. print("Didn't find a cube :-(")
  36. return
  37. finally:
  38. look_around.stop()
  39. cube.start_light_chaser()
  40. try:
  41. print("Waiting for cube to be tapped")
  42. cube.wait_for_tap(timeout=10)
  43. print("Cube tapped")
  44. except asyncio.TimeoutError:
  45. print("No-one tapped our cube :-(")
  46. finally:
  47. cube.stop_light_chaser()
  48. cube.set_lights_off()
  49. cozmo.run_program(cozmo_program)

2. 异步

立方体闪烁异步示例

注意注释(效果相似但实现过程有差异):

The async equivalent of 01_cube_blinker_sync.

    The usage of ``async def`` makes the cozmo_program method a coroutine.
    Within a coroutine, ``await`` can be used. With ``await``, the statement
    blocks until the request being waited for has completed. Meanwhile
    the event loop continues in the background.

    For instance, the statement
    ``await robot.world.wait_for_observed_light_cube(timeout=60)``
    blocks until Cozmo discovers a light cube or the 60 second timeout
    elapses, whichever occurs first.

    Likewise, the statement ``await cube.wait_for_tap(timeout=10)``
    blocks until the tap event is received or the 10 second timeout occurs,
    whichever occurs first.

    For more information, see
    https://docs.python.org/3/library/asyncio-task.html


  
  1. import asyncio
  2. import sys
  3. import cozmo
  4. class BlinkyCube(cozmo.objects.LightCube):
  5. '''Subclass LightCube and add a light-chaser effect.'''
  6. def __init__(self, *a, **kw):
  7. super().__init__(*a, **kw)
  8. self._chaser = None
  9. def start_light_chaser(self):
  10. '''Cycles the lights around the cube with 1 corner lit up green,
  11. changing to the next corner every 0.1 seconds.
  12. '''
  13. if self._chaser:
  14. raise ValueError("Light chaser already running")
  15. async def _chaser():
  16. while True:
  17. for i in range(4):
  18. cols = [cozmo.lights.off_light] * 4
  19. cols[i] = cozmo.lights.green_light
  20. self.set_light_corners(*cols)
  21. await asyncio.sleep(0.1, loop=self._loop)
  22. self._chaser = asyncio.ensure_future(_chaser(), loop=self._loop)
  23. def stop_light_chaser(self):
  24. if self._chaser:
  25. self._chaser.cancel()
  26. self._chaser = None
  27. # Make sure World knows how to instantiate the subclass
  28. cozmo.world.World.light_cube_factory = BlinkyCube
  29. async def cozmo_program(robot: cozmo.robot.Robot):
  30. '''The async equivalent of 01_cube_blinker_sync.
  31. The usage of ``async def`` makes the cozmo_program method a coroutine.
  32. Within a coroutine, ``await`` can be used. With ``await``, the statement
  33. blocks until the request being waited for has completed. Meanwhile
  34. the event loop continues in the background.
  35. For instance, the statement
  36. ``await robot.world.wait_for_observed_light_cube(timeout=60)``
  37. blocks until Cozmo discovers a light cube or the 60 second timeout
  38. elapses, whichever occurs first.
  39. Likewise, the statement ``await cube.wait_for_tap(timeout=10)``
  40. blocks until the tap event is received or the 10 second timeout occurs,
  41. whichever occurs first.
  42. For more information, see
  43. https://docs.python.org/3/library/asyncio-task.html
  44. '''
  45. cube = None
  46. look_around = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)
  47. try:
  48. cube = await robot.world.wait_for_observed_light_cube(timeout=60)
  49. except asyncio.TimeoutError:
  50. print("Didn't find a cube :-(")
  51. return
  52. finally:
  53. look_around.stop()
  54. cube.start_light_chaser()
  55. try:
  56. print("Waiting for cube to be tapped")
  57. await cube.wait_for_tap(timeout=10)
  58. print("Cube tapped")
  59. except asyncio.TimeoutError:
  60. print("No-one tapped our cube :-(")
  61. finally:
  62. cube.stop_light_chaser()
  63. cube.set_lights_off()
  64. cozmo.run_program(cozmo_program)

Fin


 

文章来源: zhangrelay.blog.csdn.net,作者:zhangrelay,版权归原作者所有,如需转载,请联系作者。

原文链接:zhangrelay.blog.csdn.net/article/details/86672049

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。