Cozmo人工智能机器人SDK使用笔记(9)判断部分if_this_then_that

版权声明:本文为zhangrelay原创文章,有错请轻拍,转载请注明,谢谢... https://blog.csdn.net/ZhangRelay/article/details/86673649

Cozmo判断部分有3个主题:

  1. gmail
  2. sport
  3. stock

1. gmail

此示例演示了如何使用“If This Then That”(http://ifttt.com)使Cozmo在Gmail帐户收到电子邮件时作出回应。以下说明将引导您在IFTTT网站上设置小程序。当调用applet触发器(发送在此示例中启动的Web服务器收到的Web请求)时,Cozmo将播放动画,说出电子邮件发件人的姓名并在他的脸上显示邮箱图像。

import asyncio
import re
import sys


try:
    from aiohttp import web
except ImportError:
    sys.exit("Cannot import from aiohttp. Do `pip3 install --user aiohttp` to install")

import cozmo

from common import IFTTTRobot


app = web.Application()


async def serve_gmail(request):
    '''Define an HTTP POST handler for receiving requests from If This Then That.

    You may modify this method to change how Cozmo reacts to the email
    being received.
    '''

    json_object = await request.json()

    # Extract the name of the email sender.
    from_email_address = json_object["FromAddress"]

    # Use a regular expression to break apart pieces of the email address
    match_object = re.search(r'([\w.]+)@([\w.]+)', from_email_address)
    email_local_part = match_object.group(1)

    robot = request.app['robot']
    async def read_name():
        try:
            async with robot.perform_off_charger():
                '''If necessary, Move Cozmo's Head and Lift to make it easy to see Cozmo's face.'''
                await robot.get_in_position()

                # First, have Cozmo play an animation
                await robot.play_anim_trigger(cozmo.anim.Triggers.ReactToPokeStartled).wait_for_completed()

                # Next, have Cozmo speak the name of the email sender.
                await robot.say_text("Email from " + email_local_part).wait_for_completed()

                # Last, have Cozmo display an email image on his face.
                robot.display_image_file_on_face("../face_images/ifttt_gmail.png")

        except cozmo.RobotBusy:
            cozmo.logger.warning("Robot was busy so didn't read email address: "+ from_email_address)

    # Perform Cozmo's task in the background so the HTTP server responds immediately.
    asyncio.ensure_future(read_name())

    return web.Response(text="OK")

# Attach the function as an HTTP handler.
app.router.add_post('/iftttGmail', serve_gmail)


if __name__ == '__main__':
    cozmo.setup_basic_logging()
    cozmo.robot.Robot.drive_off_charger_on_connect = False

    # Use our custom robot class with extra helper methods
    cozmo.conn.CozmoConnection.robot_factory = IFTTTRobot

    try:
        app_loop = asyncio.get_event_loop()  
        sdk_conn = cozmo.connect_on_loop(app_loop)

        # Wait for the robot to become available and add it to the app object.
        app['robot'] = app_loop.run_until_complete(sdk_conn.wait_for_robot())
    except cozmo.ConnectionError as e:
        sys.exit("A connection error occurred: %s" % e)

    web.run_app(app)

2. sport

此示例演示了如何使用“If This Then That”(http://ifttt.com)使Cozmo在您指定的团队进行游戏内或最终分数更新时做出响应。 以下说明将引导您在IFTTT网站上设置小程序。 当调用applet触发器(发送在此示例中启动的Web服务器接收的Web请求)时,Cozmo将播放动画,在他的脸上显示图像,并说出游戏内更新。

import asyncio
import sys


try:
    from aiohttp import web
except ImportError:
    sys.exit("Cannot import from aiohttp. Do `pip3 install --user aiohttp` to install")

import cozmo

from common import IFTTTRobot


app = web.Application()


async def serve_sports(request):
    '''Define an HTTP POST handler for receiving requests from If This Then That.

    You may modify this method to change how Cozmo reacts to
    an in-game update from IFTTT.
    '''

    json_object = await request.json()

    # Extract the text for the in-game update.
    alert_body = json_object["AlertBody"]

    robot = request.app['robot']
    async def read_name():
        try:
            async with robot.perform_off_charger():
                '''If necessary, Move Cozmo's Head and Lift to make it easy to see Cozmo's face.'''
                await robot.get_in_position()

                # First, have Cozmo play an animation
                await robot.play_anim_trigger(cozmo.anim.Triggers.ReactToPokeStartled).wait_for_completed()

                # Next, have Cozmo speak the text from the in-game update.
                await robot.say_text(alert_body).wait_for_completed()

                # Last, have Cozmo display a sports image on his face.
                robot.display_image_file_on_face("../face_images/ifttt_sports.png")

        except cozmo.RobotBusy:
            cozmo.logger.warning("Robot was busy so didn't read update: '" + alert_body +"'")

    # Perform Cozmo's task in the background so the HTTP server responds immediately.
    asyncio.ensure_future(read_name())

    return web.Response(text="OK")

# Attach the function as an HTTP handler.
app.router.add_post('/iftttSports', serve_sports)


if __name__ == '__main__':
    cozmo.setup_basic_logging()
    cozmo.robot.Robot.drive_off_charger_on_connect = False

    # Use our custom robot class with extra helper methods
    cozmo.conn.CozmoConnection.robot_factory = IFTTTRobot

    try:
        app_loop = asyncio.get_event_loop()  
        sdk_conn = cozmo.connect_on_loop(app_loop)

        # Wait for the robot to become available and add it to the app object.
        app['robot'] = app_loop.run_until_complete(sdk_conn.wait_for_robot())
    except cozmo.ConnectionError as e:
        sys.exit("A connection error occurred: %s" % e)

    web.run_app(app)

此IFTTT示例使用Flask Web框架并且是同步的,与其他异步的IFTTT示例不同并使用aiohttp。在此示例中,IFTTT Web请求由函数receive_ifttt_web_request接收。进入该方法的每个Web请求都会添加到Queue ifttt_queue,并且HTTP状态代码200或503会立即返回到IFTTT。该队列由worker函数检查,该函数在后台线程上运行(由run函数启动)。当worker函数在队列中找到新请求时,请求将从队列中删除并在方法then_that_action中处理。

与ifttt_sports.py示例一样,此示例演示了如何使用“If This Then That”(http://ifttt.com)使Cozmo在您指定的团队有游戏内或最终得分更新时做出响应。以下说明将引导您完成设置
在IFTTT网站上发布一个applet。当调用applet触发器(发送在此示例中启动的烧瓶服务器接收的Web请求)时,Cozmo将播放动画,在他的脸上显示图像,并说出游戏内更新。

import json
import queue
import sys
import threading

import cozmo
sys.path.append('../lib/')
import flask_helpers

from common import IFTTTRobot


try:
    from flask import Flask, request
except ImportError:
    sys.exit("Cannot import from flask: Do `pip3 install --user flask` to install")


flask_app = Flask(__name__)
ifttt_queue = queue.Queue()
robot = None


@flask_app.route('/iftttSports', methods=['POST'])
def receive_ifttt_web_request():
    '''Web request endpoint named "iftttSports" for IFTTT to call when a new in-game
        update for your team is posted on ESPN.

        In the IFTTT web request, in the URL field, specify this method
        as the endpoint. For instance, if your public url is http://my.url.com,
        then in the IFTTT web request URL field put the following:
        http://my.url.com/iftttSports. Then, this endpoint will be called when
        IFTTT checks and discovers that a new in-game update for your team is
        posted on ESPN.
    '''

    # Retrieve the data passed by If This Then That in the web request body.
    json_object = json.loads(request.data.decode("utf-8"))

    # Extract the text for the in-game update.
    alert_body = json_object["AlertBody"]

    # Add this request to the queue of in-game updates awaiting Cozmo's reaction.
    ifttt_queue.put((then_that_action, alert_body))

    # Return promptly so If This Then That knows that the web request was received
    # successfully.
    return ""


def then_that_action(alert_body):
    '''Controls how Cozmo responds to the in-game update.

    You may modify this method to change how Cozmo reacts to
    the update from IFTTT.
    '''

    try:
        with robot.perform_off_charger():
            '''If necessary, Move Cozmo's Head and Lift to make it easy to see Cozmo's face.'''
            robot.get_in_position()

            # First, have Cozmo play an animation
            robot.play_anim_trigger(cozmo.anim.Triggers.ReactToPokeStartled).wait_for_completed()

            # Next, have Cozmo speak the text from the in-game update.
            robot.say_text(alert_body).wait_for_completed()

            # Last, have Cozmo display a sports image on his face.
            robot.display_image_file_on_face("../face_images/ifttt_sports.png")

    except cozmo.exceptions.RobotBusy:
        pass


def worker():
    while True:
        item = ifttt_queue.get()
        if item is None:
            break
        queued_action, action_args = item
        queued_action(action_args)


def run(sdk_conn):
    global robot
    robot = sdk_conn.wait_for_robot()

    threading.Thread(target=worker).start()

    # Start flask web server so that /iftttSports can serve as endpoint.
    flask_helpers.run_flask(flask_app, "127.0.0.1", 8080, False, False)

    # Putting None on the queue stops the thread. This is called when the
    # user hits Control C, which stops the run_flask call.
    ifttt_queue.put(None)


if __name__ == '__main__':
    cozmo.setup_basic_logging()
    cozmo.robot.Robot.drive_off_charger_on_connect = False

    # Use our custom robot class with extra helper methods
    cozmo.conn.CozmoConnection.robot_factory = IFTTTRobot

    try:
        cozmo.connect(run)
    except cozmo.ConnectionError as e:
        sys.exit("A connection error occurred: %s" % e)

3. stock

此示例演示了如何使用“If This Then That”(http://ifttt.com)使Cozmo在股票代码符号增加1%或更多时作出响应。 以下说明将引导您在IFTTT网站上设置小程序。 当调用applet触发器(发送在此示例中启动的Web服务器接收的Web请求)时,Cozmo将播放动画,说出公司名称和增加的百分比,并在他的脸上显示股票市场图像。

import asyncio
import sys


try:
    from aiohttp import web
except ImportError:
    sys.exit("Cannot import from aiohttp. Do `pip3 install --user aiohttp` to install")

import cozmo

from common import IFTTTRobot


app = web.Application()


async def serve_stocks(request):
    '''Define an HTTP POST handler for receiving requests from If This Then That.

    Controls how Cozmo responds to stock notification. You may modify this method
    to change how Cozmo reacts to the stock price increasing.
    '''

    json_object = await request.json()

    # Extract the company name for the stock ticker symbol.
    stock_name = json_object["StockName"]

    # Extract the percentage increase.
    percentage = str(json_object["PercentageChange"])

    robot = request.app['robot']
    async def read_name():
        try:
            async with robot.perform_off_charger():
                '''If necessary, Move Cozmo's Head and Lift to make it easy to see Cozmo's face.'''
                await robot.get_in_position()

                # First, have Cozmo play an animation
                await robot.play_anim_trigger(cozmo.anim.Triggers.ReactToPokeStartled).wait_for_completed()

                # Next, have Cozmo say that your stock is up by x percent.
                await robot.say_text(stock_name + " is up " + percentage + " percent").wait_for_completed()

                # Last, have Cozmo display a stock market image on his face.
                robot.display_image_file_on_face("../face_images/ifttt_stocks.png")

        except cozmo.RobotBusy:
            cozmo.logger.warning("Robot was busy so didn't read stock update: '"+ stock_name + " is up " + percentage + " percent'.")

    # Perform Cozmo's task in the background so the HTTP server responds immediately.
    asyncio.ensure_future(read_name())

    return web.Response(text="OK")

# Attach the function as an HTTP handler.
app.router.add_post('/iftttStocks', serve_stocks)


if __name__ == '__main__':
    cozmo.setup_basic_logging()
    cozmo.robot.Robot.drive_off_charger_on_connect = False

    # Use our custom robot class with extra helper methods
    cozmo.conn.CozmoConnection.robot_factory = IFTTTRobot

    try:
        app_loop = asyncio.get_event_loop()  
        sdk_conn = cozmo.connect_on_loop(app_loop)

        # Wait for the robot to become available and add it to the app object.
        app['robot'] = app_loop.run_until_complete(sdk_conn.wait_for_robot())
    except cozmo.ConnectionError as e:
        sys.exit("A connection error occurred: %s" % e)

    web.run_app(app)

Fin


猜你喜欢

转载自blog.csdn.net/ZhangRelay/article/details/86673649
今日推荐