前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Cozmo人工智能机器人SDK使用笔记(5)-时序部分async_sync

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

作者头像
zhangrelay
发布2019-01-31 16:04:54
4880
发布2019-01-31 16:04:54
举报
文章被收录于专栏:机器人课程与技术

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

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


1. 同步

立方体闪烁同步示例

代码语言:javascript
复制
import asyncio
import sys

import cozmo

class BlinkyCube(cozmo.objects.LightCube):
    '''Subclass LightCube and add a light-chaser effect.'''
    def __init__(self, *a, **kw):
        super().__init__(*a, **kw)
        self._chaser = None

    def start_light_chaser(self):
        '''Cycles the lights around the cube with 1 corner lit up green,
        changing to the next corner every 0.1 seconds.
        '''
        if self._chaser:
            raise ValueError("Light chaser already running")
        async def _chaser():
            while True:
                for i in range(4):
                    cols = [cozmo.lights.off_light] * 4
                    cols[i] = cozmo.lights.green_light
                    self.set_light_corners(*cols)
                    await asyncio.sleep(0.1, loop=self._loop)
        self._chaser = asyncio.ensure_future(_chaser(), loop=self._loop)

    def stop_light_chaser(self):
        if self._chaser:
            self._chaser.cancel()
            self._chaser = None


# Make sure World knows how to instantiate the subclass
cozmo.world.World.light_cube_factory = BlinkyCube


def cozmo_program(robot: cozmo.robot.Robot):
    cube = None
    look_around = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)

    try:
        cube = robot.world.wait_for_observed_light_cube(timeout=60)
    except asyncio.TimeoutError:
        print("Didn't find a cube :-(")
        return
    finally:
        look_around.stop()

    cube.start_light_chaser()
    try:
        print("Waiting for cube to be tapped")
        cube.wait_for_tap(timeout=10)
        print("Cube tapped")
    except asyncio.TimeoutError:
        print("No-one tapped our cube :-(")
    finally:
        cube.stop_light_chaser()
        cube.set_lights_off()


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

代码语言:javascript
复制
import asyncio
import sys

import cozmo

class BlinkyCube(cozmo.objects.LightCube):
    '''Subclass LightCube and add a light-chaser effect.'''
    def __init__(self, *a, **kw):
        super().__init__(*a, **kw)
        self._chaser = None

    def start_light_chaser(self):
        '''Cycles the lights around the cube with 1 corner lit up green,
        changing to the next corner every 0.1 seconds.
        '''
        if self._chaser:
            raise ValueError("Light chaser already running")
        async def _chaser():
            while True:
                for i in range(4):
                    cols = [cozmo.lights.off_light] * 4
                    cols[i] = cozmo.lights.green_light
                    self.set_light_corners(*cols)
                    await asyncio.sleep(0.1, loop=self._loop)
        self._chaser = asyncio.ensure_future(_chaser(), loop=self._loop)

    def stop_light_chaser(self):
        if self._chaser:
            self._chaser.cancel()
            self._chaser = None


# Make sure World knows how to instantiate the subclass
cozmo.world.World.light_cube_factory = BlinkyCube


async def cozmo_program(robot: cozmo.robot.Robot):
    '''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
    '''

    cube = None
    look_around = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)

    try:
        cube = await robot.world.wait_for_observed_light_cube(timeout=60)
    except asyncio.TimeoutError:
        print("Didn't find a cube :-(")
        return
    finally:
        look_around.stop()

    cube.start_light_chaser()
    try:
        print("Waiting for cube to be tapped")
        await cube.wait_for_tap(timeout=10)
        print("Cube tapped")
    except asyncio.TimeoutError:
        print("No-one tapped our cube :-(")
    finally:
        cube.stop_light_chaser()
        cube.set_lights_off()


cozmo.run_program(cozmo_program)

Fin


本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年01月28日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档