专栏首页机器人课程与技术Cozmo人工智能机器人SDK使用笔记(5)-时序部分async_sync

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

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

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


1. 同步

立方体闪烁同步示例

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

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


本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 机器人控制器编程课程-教案02-基础

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    zhangrelay
  • 机器人体验营笔记(三)进阶

    版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons)

    zhangrelay
  • Gazebo機器人仿真學習探索筆記(一)安裝與使用

    Gazebo提供了多平臺的安裝和使用支持,大部分主流的linux,Mac以及Windows,這裏結合ROS以Ubuntu爲例進行介紹。

    zhangrelay
  • python开发_tkinter_获取文本框内容_给文本框添加键盘输入事件

    ==========================================================

    Hongten
  • DIY打造71TB的NAS存储

    下面是我打造的71TB的Linux ZFS存储系统,目前稳定运行快两年了。所以下面我将分享我的配置过程。

    木子-Lee
  • 【程序源代码】工作流Activiti不错的学习资料总结

    在第一家公司工作的时候主要任务就是开发OA系统,当然基本都是有工作流的支持,不过当时使用的工作流引擎是公司一些牛人开发的(据说是用一个开源的引擎修改的),名称叫...

    程序源代码
  • 用树莓派搭建一个实时视频监控系统

    最近在GitHub上发现一个好玩的项目,不用安装其它任何依赖包,只要运行一个Python脚本就可以搭建一个实时视频监控系统。

    小雨编程
  • 004.ELK-6.6.0安装部署

    CoderJed
  • python实现朴素贝叶斯

    朴素贝叶斯是jiyu贝叶斯定理和特征条件独立假设的分类方法。即对于给定训练数据集,首先基于特征条件独立假设学习输入\输出的联合概率分布,然后基于此模型,对于给定...

    绝命生
  • 【CodeForces 599A】D - 特别水的题4- Patrick and Shopping

    Today Patrick waits for a visit from his friend Spongebob. To prepare for the vi...

    饶文津

扫码关注云+社区

领取腾讯云代金券