Nino Guba
Published © GPL3+

LEGO Target Practice powered by Mindstorms EV3 and Alexa

Be a sharpshooter! Perfect your aim with this dueling tree target practice gadget powered by LEGO Mindstorms EV3 and Alexa.

IntermediateFull instructions provided2 hours398

Things used in this project

Hardware components

EV3 Programming Brick / Kit
LEGO MindStorms EV3 Programming Brick / Kit
Most LEGO pieces used in this project are from the Education EV3 Core + Expansion sets and a few LEGO Classic plates.
×1
Echo Dot
Amazon Alexa Echo Dot
Or any compatible Echo devices that supports gadgets
×1
Micro SD card (minimum 8GB)
×1
Computer for installing software and programming your EV3 Brick
×1
WiFi USB adapter or USB cable for connecting to your EV3 Brick and running programs
×1

Software apps and online services

Visual Studio Code
ev3dev
Sign up for an Amazon Developer account to register your gadget and create your Alexa skill

Story

Read more

Schematics

Build Instructions

Additional Instructions: 1) Connect the cables to the large motors and to the EV3 Brick from top to bottom onto ports A to D 2) Connect the cables to the touch sensors and to the EV3 Brick with the left to port 2 and right to port 3 3) Tuck the cables behind the shields

LEGO Parts List

All the LEGO parts used to build the gadget.

Code

target-practice.py

Python
Copy and paste this for the EV3 Python code.
#!/usr/bin/env python3
# Copyright 2019 Nino Guba. All Rights Reserved.

import os
import sys
import time
import logging
import json
import random
import threading

from enum import Enum
from agt import AlexaGadget
from time import sleep

from ev3dev2.led import Leds
from ev3dev2.sound import Sound
from ev3dev2.motor import OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D, SpeedPercent, LargeMotor
from ev3dev2.sensor import INPUT_2, INPUT_3
from ev3dev2.sensor.lego import TouchSensor, UltrasonicSensor

# Set the logging level to INFO to see messages from AlexaGadget
logging.basicConfig(level=logging.INFO, stream=sys.stdout, format='%(message)s')
logging.getLogger().addHandler(logging.StreamHandler(sys.stderr))
logger = logging.getLogger(__name__)


class Mode(Enum):
    """
    The list of preset modes and their invocation variation.
    These variations correspond to the skill slot values.
    """
    SOLO = ['solo', 'single', 'one player']
    DUEL = ['dual', 'duel', 'multiplayer', 'two players']
    UNLIMITED = ['unlimited', 'unlimited ammo']

class EventName(Enum):
    """
    The list of custom event name sent from this gadget
    """
    READY = "Ready"
    WINNER = "Winner"
    RED = "Red"
    BLUE = "Blue"
    SPEECH = "Speech"
    HIT = "Hit"
    BONUS = "Bonus"

class MindstormsGadget(AlexaGadget):
    """
    A Mindstorms gadget that performs movement based on voice commands.
    """

    def __init__(self):
        """
        Performs Alexa Gadget initialization routines and ev3dev resource allocation.
        """
        super().__init__()

        # Gadget state
        self.solo_mode = False
        self.unlimited_mode = False
        self.game_started = False

        # Ev3dev initialization
        self.leds = Leds()
        self.sound = Sound()
        self.target1 = LargeMotor(OUTPUT_A)
        self.target2 = LargeMotor(OUTPUT_B)
        self.target3 = LargeMotor(OUTPUT_C)
        self.target4 = LargeMotor(OUTPUT_D)
        self.targetB = TouchSensor(INPUT_2)
        self.targetR = TouchSensor(INPUT_3)
        #self.ultrasonic = UltrasonicSensor()

        # Start threads
        threading.Thread(target=self._game_thread, daemon=True).start()
        threading.Thread(target=self._bonus_target_thread, args=(self.targetR, 1,), daemon=True).start()
        threading.Thread(target=self._bonus_target_thread, args=(self.targetB, 2,), daemon=True).start()
        threading.Thread(target=self._target_thread, args=(self.target1, 1,), daemon=True).start()
        threading.Thread(target=self._target_thread, args=(self.target2, 2,), daemon=True).start()
        threading.Thread(target=self._target_thread, args=(self.target3, 3,), daemon=True).start()
        threading.Thread(target=self._target_thread, args=(self.target4, 4,), daemon=True).start()

    def on_connected(self, device_addr):
        """
        Gadget connected to the paired Echo device.
        :param device_addr: the address of the device we connected to
        """
        self.leds.set_color("LEFT", "GREEN")
        self.leds.set_color("RIGHT", "GREEN")
        logger.info("{} connected to Echo device".format(self.friendly_name))

    def on_disconnected(self, device_addr):
        """
        Gadget disconnected from the paired Echo device.
        :param device_addr: the address of the device we disconnected from
        """
        self.leds.set_color("LEFT", "BLACK")
        self.leds.set_color("RIGHT", "BLACK")
        logger.info("{} disconnected from Echo device".format(self.friendly_name))

    def on_custom_mindstorms_gadget_control(self, directive):
        """
        Handles the Custom.Mindstorms.Gadget control directive.
        :param directive: the custom directive with the matching namespace and name
        """
        try:
            payload = json.loads(directive.payload.decode("utf-8"))
            print("Control payload: {}".format(payload), file=sys.stderr)
            control_type = payload["type"]

            if control_type == "mode":
                # Expected params: [mode]
                self._start(payload["mode"])

        except KeyError:
            print("Missing expected parameters: {}".format(directive), file=sys.stderr)

    def _start(self, mode):
        """
        Sets the game mode.
        :param mode: the preset mode
        """
        print("Mode command: ({})".format(mode), file=sys.stderr)
        if mode in Mode.SOLO.value:
            self.solo_mode = True
            self.unlimited_mode = False

        if mode in Mode.DUEL.value:
            self.solo_mode = False
            self.unlimited_mode = False

        if mode in Mode.UNLIMITED.value:
            self.solo_mode = False
            self.unlimited_mode = True

        # Reset to start position
        self._reset()

        # Initialize the game
        self.game_started = False
        self.targets_is_hit = [False,False,False,False]
        self.targets_on_red = [True,True,True,True]

        # For duels, alternate targets on either sides
        if not(self.solo_mode):
            self.target2.on_to_position(SpeedPercent(25), 180, brake=False, block=True)
            #self.target2.on_for_degrees(SpeedPercent(25), 178, brake=False, block=True)
            self.targets_on_red[1] = False
            self.target4.on_to_position(SpeedPercent(25), 180, brake=False, block=True)
            #self.target4.on_for_degrees(SpeedPercent(25), 178, brake=False, block=True)
            self.targets_on_red[3] = False
            time.sleep(1)

        # Start the game
        print("Targets ready...", file=sys.stderr)
        self._send_event(EventName.READY, {})
        self.game_started = True

    def _target_thread(self, target, index):
        """
        Performs the side switch when the target gets hit
        """
        while True:
            while self.game_started:
                curr_position = target.position
                target_on_red = curr_position < 90

                if target.position != curr_position and abs(target.position - curr_position) < 5:
                    self.leds.set_color("RIGHT" if target_on_red else "LEFT", "RED")
                    self.leds.set_color("RIGHT" if target_on_red else "LEFT", "GREEN")
                    target_string = "Target {} is hit!".format(index)
                    self._send_event(EventName.HIT, {'speechOut': target_string})
                    print(target_string, file=sys.stderr)
                    target.on_to_position(SpeedPercent(35), 180 if target_on_red else 0, brake=True, block=True)
                    #target.on_for_degrees(SpeedPercent(35), 178 if target_on_red else -178, brake=True, block=True)
                    #target.on_for_rotations(SpeedPercent(35), 0.5 if target_on_red else -0.5, brake=True, block=False)
                    #target.wait_until_not_moving()
                    #target.off()
                    target_on_red = not target_on_red
                    self.targets_on_red[index-1] = target_on_red
                    time.sleep(1)
                    curr_position = target.position
                    self.targets_is_hit[index-1] = True

    def _bonus_target_thread(self, target, index):
        """
        Performs the score when the bonus target gets hit
        """
        target_is_red = (index == 1)

        while True:
            while self.game_started:
                target.wait_for_bump()
                self.leds.set_color("RIGHT" if target_is_red else "LEFT", "RED")
                self.leds.set_color("RIGHT" if target_is_red else "LEFT", "GREEN")
                target_string = "Bonus target {} is hit!".format(index)
                self._send_event(EventName.BONUS, {'speechOut': target_string})
                print(target_string, file=sys.stderr)

    def _game_thread(self):
        """
        Watches the targets to determine when the game is over and who is the winner
        """
        while True:
            while self.game_started:
                game_over = False

                if self.unlimited_mode:
                    # In unlimited mode, the game can only be over if stopped or mode is changed
                    game_over = False

                elif not(self.solo_mode):
                    # In duel mode, the game is won when you've hit all targets and they are all on the opponent's side
                    if (self.targets_is_hit[0] or self.targets_is_hit[1] or self.targets_is_hit[2] or self.targets_is_hit[3]) and self.targets_on_red[0] and self.targets_on_red[1] and self.targets_on_red[2] and self.targets_on_red[3]:
                        winner = "Blue"
                        game_over = True
                    elif (self.targets_is_hit[0] or self.targets_is_hit[1] or self.targets_is_hit[2] or self.targets_is_hit[3]) and not(self.targets_on_red[0]) and not(self.targets_on_red[1]) and not(self.targets_on_red[2]) and not(self.targets_on_red[3]):
                        winner = "Red"
                        game_over = True
                else:
                    # In solo mode, the game is won when you've hit all targets on one side then hit them all again on the other side
                    if self.targets_is_hit[0] and self.targets_is_hit[1] and self.targets_is_hit[2] and self.targets_is_hit[3] and self.targets_on_red[0] and self.targets_on_red[1] and self.targets_on_red[2] and self.targets_on_red[3]:
                        winner = "Red"
                        game_over = True

                if game_over:
                    self.game_started = False
                    target_string = "{} won!".format(winner) if not(self.solo_mode) else ""
                    self._send_event(EventName.WINNER, {'speechOut': target_string, 'winner': winner})
                    print(target_string, file=sys.stderr)

                time.sleep(1)

    def _reset(self):
        """
        Resets targets to start position.
        """
        self.target1.on_for_rotations(SpeedPercent(15), -1, brake=True, block=False)
        self.target2.on_for_rotations(SpeedPercent(15), -1, brake=True, block=False)
        self.target3.on_for_rotations(SpeedPercent(15), -1, brake=True, block=False)
        self.target4.on_for_rotations(SpeedPercent(15), -1, brake=True, block=False)
        self.target1.wait_until_not_moving()
        self.target1.off()
        self.target1.position = 0
        self.target2.wait_until_not_moving()
        self.target2.off()
        self.target2.position = 0
        self.target3.wait_until_not_moving()
        self.target3.off()
        self.target3.position = 0
        self.target4.wait_until_not_moving()
        self.target4.off()
        self.target4.position = 0
        """
        self.target1.on_for_degrees(SpeedPercent(15), 178, brake=False, block=True)
        self.target2.on_for_degrees(SpeedPercent(15), 178, brake=False, block=True)
        self.target3.on_for_degrees(SpeedPercent(15), 178, brake=False, block=True)
        self.target4.on_for_degrees(SpeedPercent(15), 178, brake=False, block=True)
        self.target1.on_for_degrees(SpeedPercent(15), -178, brake=True, block=True)
        self.target2.on_for_degrees(SpeedPercent(15), -178, brake=True, block=True)
        self.target3.on_for_degrees(SpeedPercent(15), -178, brake=True, block=True)
        self.target4.on_for_degrees(SpeedPercent(15), -178, brake=True, block=True)
        """
        self.target1.off(brake=False)
        self.target2.off(brake=False)
        self.target3.off(brake=False)
        self.target4.off(brake=False)
        print("Targets reset to start position.", file=sys.stderr)

    def _send_event(self, name: EventName, payload):
        """
        Sends a custom event to trigger a sentry action.
        :param name: the name of the custom event
        :param payload: the sentry JSON payload
        """
        self.send_custom_event('Custom.Mindstorms.Gadget', name.value, payload)

if __name__ == '__main__':

    gadget = MindstormsGadget()

    # Set LCD font and turn off blinking LEDs
    os.system('setfont Lat7-Terminus12x6')
    gadget.leds.set_color("LEFT", "BLACK")
    gadget.leds.set_color("RIGHT", "BLACK")

    # Startup sequence
    gadget.sound.play_song((('C4', 'e'), ('D4', 'e'), ('E5', 'q')))
    gadget.leds.set_color("LEFT", "GREEN")
    gadget.leds.set_color("RIGHT", "GREEN")

    # Reset to start position
    gadget._reset()
    
    # Gadget main entry point
    gadget.main()

    # Shutdown sequence
    gadget.sound.play_song((('E5', 'e'), ('C4', 'e')))
    gadget.leds.set_color("LEFT", "BLACK")
    gadget.leds.set_color("RIGHT", "BLACK")

target-practice.ini

Python
Copy and paste this for the EV3 Python code.
# Copyright 2019 Nino Guba.  All Rights Reserved.

[GadgetSettings]
amazonId = CHANGE_THIS
alexaGadgetSecret = CHANGE_THIS

[GadgetCapabilities]
Custom.Mindstorms.Gadget = 1.0

model.json

JSON
Copy and paste this JSON in your Alexa Skill Interaction Model
{
    "interactionModel": {
        "languageModel": {
            "invocationName": "target practice",
            "intents": [
                {
                    "name": "AMAZON.CancelIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.HelpIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.StopIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.NavigateHomeIntent",
                    "samples": []
                },
                {
                    "name": "ModeIntent",
                    "slots": [
                        {
                            "name": "Mode",
                            "type": "ModeType"
                        }
                    ],
                    "samples": [
                        "Play game in {Mode} mode",
                        "Play {Mode}",
                        "Start {Mode}",
                        "Start game in {Mode} mode",
                        "Play game",
                        "Start game",
                        "Play",
                        "Start"
                    ]
                },
                {
                    "name": "AMAZON.YesIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.NoIntent",
                    "samples": []
                }
            ],
            "types": [
                {
                    "name": "ModeType",
                    "values": [
                        {
                            "name": {
                                "value": "duel"
                            }
                        },
                        {
                            "name": {
                                "value": "dual"
                            }
                        },
                        {
                            "name": {
                                "value": "multiplayer"
                            }
                        },
                        {
                            "name": {
                                "value": "two player"
                            }
                        },
                        {
                            "name": {
                                "value": "solo"
                            }
                        },
                        {
                            "name": {
                                "value": "one player"
                            }
                        },
                        {
                            "name": {
                                "value": "single player"
                            }
                        },
                        {
                            "name": {
                                "value": "unlimited"
                            }
                        },
                        {
                            "name": {
                                "value": "unlimited ammo"
                            }
                        }
                    ]
                }
            ]
        }
    }
}

index.js

JavaScript
Copy and paste this for the Alexa Skill lambda code.
/*
 * Copyright 2019 Nino Guba.  All Rights Reserved.
*/

const Alexa = require('ask-sdk-core');
const Util = require('./util');
const Common = require('./common');

// The audio tag to include background music
const BG_MUSIC = '<audio src="soundbank://soundlibrary/ui/gameshow/amzn_ui_sfx_gameshow_waiting_loop_30s_01"></audio>';

// The namespace of the custom directive to be sent by this skill
const NAMESPACE = 'Custom.Mindstorms.Gadget';

// The name of the custom directive to be sent this skill
const NAME_CONTROL = 'control';

const WINNER_SPEECHCONS = ['Bingo', 'Bravo', 'Cheers', 'Hip hip hooray', 'Hurrah', 'Oh snap', 'Way to go', 'Well done', 'Whee', 'Woo hoo', 'Yay', 'Wowza', 'Yowsa']; 
const BONUS_SPEECHCONS = ['bam','bang','boom', 'booya', 'ding', 'kablam', 'kapow', 'kaboom', 'pop', 'pow'];

const LaunchRequestHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest';
    },
    handle: async function(handlerInput) {

        const request = handlerInput.requestEnvelope;
        const { apiEndpoint, apiAccessToken } = request.context.System;
        const apiResponse = await Util.getConnectedEndpoints(apiEndpoint, apiAccessToken);
        if ((apiResponse.endpoints || []).length === 0) {
            return handlerInput.responseBuilder
            .speak("I couldn't find an EV3 Brick connected to this Echo device. Please check to make sure your EV3 Brick is connected, and try again.")
            .getResponse();
        }

        // Store the gadget endpointId to be used in this skill session
        const endpointId = apiResponse.endpoints[0].endpointId || [];
        Util.putSessionAttribute(handlerInput, 'endpointId', endpointId);

        // Set skill duration to 5 minutes (ten 30-seconds interval)
        Util.putSessionAttribute(handlerInput, 'duration', 10);

        // Set the token to track the event handler
        const token = handlerInput.requestEnvelope.request.requestId;
        Util.putSessionAttribute(handlerInput, 'token', token);

        let speechOutput = "Welcome to target practice! What mode would you like to play?";
        return handlerInput.responseBuilder
            .speak(speechOutput + BG_MUSIC)
            .addDirective(Util.buildStartEventHandler(token,60000, {}))
            .getResponse();
    }
};

// Add the mode value to the session attribute.
// This allows other intent handler to use the specified mode value
// without asking the user for input.
const ModeIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'ModeIntent';
    },
    handle: function (handlerInput) {

        let mode = Alexa.getSlotValue(handlerInput.requestEnvelope, 'Mode');
        if (!mode) {
            return handlerInput.responseBuilder
                .speak("Can you repeat that?")
                .reprompt("What mode would you like to play?")
                .withShouldEndSession(false)
                .getResponse();
        }
        Util.putSessionAttribute(handlerInput, 'mode', mode);

        // Get data from session attribute
        const attributesManager = handlerInput.attributesManager;
        const endpointId = attributesManager.getSessionAttributes().endpointId || [];

        // Construct the directive with the payload containing the move parameters
        let directive = Util.build(endpointId, NAMESPACE, NAME_CONTROL,
            {
                type: 'mode',
                mode: mode
            });

        let speechOutput = `OK ${mode}`;
        return handlerInput.responseBuilder
            .speak(speechOutput + BG_MUSIC)
            .reprompt("What mode would you like to play?")
            .addDirective(directive)
            .getResponse();
    }
};

const EventsReceivedRequestHandler = {
    // Checks for a valid token and endpoint.
    canHandle(handlerInput) {
        let { request } = handlerInput.requestEnvelope;
        console.log('Request type: ' + Alexa.getRequestType(handlerInput.requestEnvelope));
        if (request.type !== 'CustomInterfaceController.EventsReceived') return false;

        const attributesManager = handlerInput.attributesManager;
        let sessionAttributes = attributesManager.getSessionAttributes();
        let customEvent = request.events[0];

        // Validate event token
        if (sessionAttributes.token !== request.token) {
            console.log("Event token doesn't match. Ignoring this event");
            return false;
        }

        // Validate endpoint
        let requestEndpoint = customEvent.endpoint.endpointId;
        if (requestEndpoint !== sessionAttributes.endpointId) {
            console.log("Event endpoint id doesn't match. Ignoring this event");
            return false;
        }
        return true;
    },
    handle(handlerInput) {

        console.log("== Received Custom Event ==");
        let customEvent = handlerInput.requestEnvelope.request.events[0];
        let payload = customEvent.payload;
        let name = customEvent.header.name;

        let speechOutput;
        if (name === 'Ready') {
            speechOutput = "<amazon:emotion name=\"excited\" intensity=\"high\">Targets ready, go shoot!</amazon:emotion>";

        } else if (name === 'Hit') {
            speechOutput = "<audio src=\"soundbank://soundlibrary/alarms/beeps_and_bloops/bell_01\"></audio>";

        } else if (name === 'Bonus') {
            speechOutput = "<say-as interpret-as=\"interjection\">"+ randomPhrase(BONUS_SPEECHCONS) +"!</say-as>";

        } else if (name === 'Winner') {
            let speechOutput = "<say-as interpret-as=\"interjection\">"+ randomPhrase(WINNER_SPEECHCONS) +"!</say-as><amazon:emotion name=\"excited\" intensity=\"high\">" + payload.speechOut + "Would you like to play again?</amazon:emotion>";
            return handlerInput.responseBuilder
            .speak(speechOutput, "REPLACE_ALL")
            .withShouldEndSession(false)
            .getResponse();

        } else if (name === 'Speech') {
            speechOutput = payload.speechOut;

        } else {
            speechOutput = "Hmmm. I don't know how to handle that...";
        }
        return handlerInput.responseBuilder
            .speak(speechOutput + BG_MUSIC, "REPLACE_ALL")
            .getResponse();
    }
};

const YesIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.YesIntent';
    },
    handle: function (handlerInput) {

        // Get data from session attribute
        const attributesManager = handlerInput.attributesManager;
        const endpointId = attributesManager.getSessionAttributes().endpointId || [];
        
        let mode = attributesManager.getSessionAttributes().mode;
        if (!mode) {
            return handlerInput.responseBuilder
                .speak("Can you repeat that?")
                .reprompt("What mode would you like to play?")
                .withShouldEndSession(false)
                .getResponse();
        }

        // Construct the directive with the payload containing the move parameters
        let directive = Util.build(endpointId, NAMESPACE, NAME_CONTROL,
            {
                type: 'mode',
                mode: mode
            });

        let speechOutput = `Ok starting`;
        return handlerInput.responseBuilder
            .speak(speechOutput + BG_MUSIC)
            .reprompt("What mode would you like to play?")
            .addDirective(directive)
            .getResponse();
    }
};

const ExpiredRequestHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'CustomInterfaceController.Expired'
    },
    handle(handlerInput) {
        console.log("== Custom Event Expiration Input ==");

        // Set the token to track the event handler
        const token = handlerInput.requestEnvelope.request.requestId;
        Util.putSessionAttribute(handlerInput, 'token', token);

        const attributesManager = handlerInput.attributesManager;
        let duration = attributesManager.getSessionAttributes().duration || 0;
        if (duration > 0) {
            Util.putSessionAttribute(handlerInput, 'duration', --duration);

            // Extends skill session
            const speechOutput = `${duration} minutes remaining.`;
            return handlerInput.responseBuilder
                .addDirective(Util.buildStartEventHandler(token, 60000, {}))
                .speak(speechOutput + BG_MUSIC)
                .getResponse();
        }
        else {
            // End skill session
            return handlerInput.responseBuilder
                .speak("Target practice skill duration expired. Goodbye.")
                .withShouldEndSession(true)
                .getResponse();
        }
    }
};

// The SkillBuilder acts as the entry point for your skill, routing all request and response
// payloads to the handlers above. Make sure any new handlers or interceptors you've
// defined are included below. The order matters - they're processed top to bottom.
exports.handler = Alexa.SkillBuilders.custom()
    .addRequestHandlers(
        LaunchRequestHandler,
        ModeIntentHandler,
        YesIntentHandler,
        EventsReceivedRequestHandler,
        ExpiredRequestHandler,
        Common.HelpIntentHandler,
        Common.CancelAndStopIntentHandler,
        Common.SessionEndedRequestHandler,
        Common.IntentReflectorHandler, // make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers
    )
    .addRequestInterceptors(Common.RequestInterceptor)
    .addErrorHandlers(
        Common.ErrorHandler,
    )
    .lambda();
    
function randomPhrase(words) {
    var i = 0;
    i = Math.floor(Math.random() * words.length);
    return(words[i]);
}

common.js

JavaScript
Copy and paste this for the Alexa Skill lambda code.
/*
 * Copyright 2019 Nino Guba.  All Rights Reserved.
*/
'use strict'

const Alexa = require('ask-sdk-core');

const HelpIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.HelpIntent';
    },
    handle(handlerInput) {
        const speakOutput = 'You can say start game to begin target practice!';

        return handlerInput.responseBuilder
            .speak(speakOutput)
            .reprompt(speakOutput)
            .getResponse();
    }
};
const CancelAndStopIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && (Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.CancelIntent'
                || Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.StopIntent'
                || Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.NoIntent');
    },
    handle(handlerInput) {
        const speakOutput = 'Goodbye!';
        return handlerInput.responseBuilder
            .speak(speakOutput)
            .getResponse();
    }
};
const SessionEndedRequestHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'SessionEndedRequest';
    },
    handle(handlerInput) {
        // Any cleanup logic goes here.
        return handlerInput.responseBuilder.getResponse();
    }
};

// The intent reflector is used for interaction model testing and debugging.
// It will simply repeat the intent the user said. You can create custom handlers
// for your intents by defining them above, then also adding them to the request
// handler chain below.
const IntentReflectorHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest';
    },
    handle(handlerInput) {
        const intentName = Alexa.getIntentName(handlerInput.requestEnvelope);
        const speakOutput = `You just triggered ${intentName}`;

        return handlerInput.responseBuilder
            .speak(speakOutput)
            .reprompt("I don't understand this command, try again")
            .getResponse();
    }
};

// Generic error handling to capture any syntax or routing errors. If you receive an error
// stating the request handler chain is not found, you have not implemented a handler for
// the intent being invoked or included it in the skill builder below.
const ErrorHandler = {
    canHandle() {
        return true;
    },
    handle(handlerInput, error) {
        console.log(`~~~~ Error handled: ${error.stack}`);
        const speakOutput = `Sorry, I had trouble doing what you asked. Please try again.`;

        return handlerInput.responseBuilder
            .speak(speakOutput)
            .reprompt(speakOutput)
            .getResponse();
    }
};

// The request interceptor is used for request handling testing and debugging.
// It will simply log the request in raw json format before any processing is performed.
const RequestInterceptor = {
    process(handlerInput) {
        let { attributesManager, requestEnvelope } = handlerInput;
        let sessionAttributes = attributesManager.getSessionAttributes();

        // Log the request for debug purposes.
        console.log(`=====Request==${JSON.stringify(requestEnvelope)}`);
        console.log(`=========SessionAttributes==${JSON.stringify(sessionAttributes, null, 2)}`);
    }
};

module.exports = {
    HelpIntentHandler,
    CancelAndStopIntentHandler,
    SessionEndedRequestHandler,
    IntentReflectorHandler,
    ErrorHandler,
    RequestInterceptor
};

util.js

JavaScript
Copy and paste this for the Alexa Skill lambda code.
/*
 * Copyright 2019 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
 *
 * You may not use this file except in compliance with the terms and conditions
 * set forth in the accompanying LICENSE.TXT file.
 *
 * THESE MATERIALS ARE PROVIDED ON AN "AS IS" BASIS. AMAZON SPECIFICALLY DISCLAIMS, WITH
 * RESPECT TO THESE MATERIALS, ALL WARRANTIES, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
*/

'use strict';

const Https = require('https');
const AWS = require('aws-sdk');
const Escape = require('lodash/escape');

const s3SigV4Client = new AWS.S3({
    signatureVersion: 'v4'
});

/**
 * Get the authenticated URL to access the S3 Object. This URL expires after 60 seconds.
 * @param s3ObjectKey - the S3 object key
 * @returns {string} the pre-signed S3 URL
 */
exports.getS3PreSignedUrl = function getS3PreSignedUrl(s3ObjectKey) {

    const bucketName = process.env.S3_PERSISTENCE_BUCKET;
    return Escape(s3SigV4Client.getSignedUrl('getObject', {
        Bucket: bucketName,
        Key: s3ObjectKey,
        Expires: 60 // the Expires is capped for 1 minute
    }));
};

/**
 * Builds a directive to start the EventHandler.
 * @param token - a unique identifier to track the event handler
 * @param {number} timeout - the duration to wait before sending back the expiration
 * payload to the skill.
 * @param payload - the expiration json payload
 * @see {@link https://developer.amazon.com/docs/alexa-gadgets-toolkit/receive-custom-event-from-gadget.html#start}
 */
exports.buildStartEventHandler = function (token, timeout = 30000, payload)  {
    return {
        type: "CustomInterfaceController.StartEventHandler",
        token: token,
        expiration : {
            durationInMilliseconds: timeout,
            expirationPayload: payload
        }
    };
};

/**
 *
 * Builds a directive to stops the active event handler.
 * The event handler is identified by the cached token in the session attribute.
 * @param {string} handlerInput - the context from Alexa Service
 * @see {@link https://developer.amazon.com/docs/alexa-gadgets-toolkit/receive-custom-event-from-gadget.html#stop}
 */
exports.buildStopEventHandlerDirective = function (handlerInput) {

    let token = handlerInput.attributesManager.getSessionAttributes().token || '';
    return {
        "type": "CustomInterfaceController.StopEventHandler",
        "token": token
    }
};

/**
 * Build a custom directive payload to the gadget with the specified endpointId
 * @param {string} endpointId - the gadget endpoint Id
 * @param {string} namespace - the namespace of the skill
 * @param {string} name - the name of the skill within the scope of this namespace
 * @param {object} payload - the payload data
 * @see {@link https://developer.amazon.com/docs/alexa-gadgets-toolkit/send-gadget-custom-directive-from-skill.html#respond}
 */
exports.build = function (endpointId, namespace, name, payload) {
    // Construct the custom directive that needs to be sent
    // Gadget should declare the capabilities in the discovery response to
    // receive the directives under the following namespace.
    return {
        type: 'CustomInterfaceController.SendDirective',
        header: {
            name: name,
            namespace: namespace
        },
        endpoint: {
            endpointId: endpointId
        },
        payload
    };
};

/**
 * A convenience routine to add the a key-value pair to the session attribute.
 * @param handlerInput - the context from Alexa Service
 * @param key - the key to be added
 * @param value - the value be added
 */
exports.putSessionAttribute = function(handlerInput, key, value) {
    const attributesManager = handlerInput.attributesManager;
    let sessionAttributes = attributesManager.getSessionAttributes();
    sessionAttributes[key] = value;
    attributesManager.setSessionAttributes(sessionAttributes);
};


/**
 * To get a list of all the gadgets that meet these conditions,
 * Call the Endpoint Enumeration API with the apiEndpoint and apiAccessToken to
 * retrieve the list of all connected gadgets.
 *
 * @param {string} apiEndpoint - the Endpoint API url
 * @param {string} apiAccessToken  - the token from the session object in the Alexa request
 * @see {@link https://developer.amazon.com/docs/alexa-gadgets-toolkit/send-gadget-custom-directive-from-skill.html#call-endpoint-enumeration-api}
 */
exports.getConnectedEndpoints = function(apiEndpoint, apiAccessToken) {

    // The preceding https:// need to be stripped off before making the call
    apiEndpoint = (apiEndpoint || '').replace('https://', '');

    return new Promise(((resolve, reject) => {

        const options = {
            host: apiEndpoint,
            path: '/v1/endpoints',
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + apiAccessToken
            }
        };

        const request = Https.request(options, (response) => {
            response.setEncoding('utf8');
            let returnData = '';
            response.on('data', (chunk) => {
                returnData += chunk;
            });

            response.on('end', () => {
                resolve(JSON.parse(returnData));
            });

            response.on('error', (error) => {
                reject(error);
            });
        });
        request.end();
    }));
};

package.json

JSON
Copy and paste this for the Alexa Skill lambda code.
{
  "name": "agt-mindstorms",
  "version": "1.1.0",
  "description": "A sample skill demonstrating how to use AGT with Lego Mindstorms",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Amazon Alexa",
  "license": "ISC",
  "dependencies": {
    "ask-sdk-core": "^2.6.0",
    "ask-sdk-model": "^1.18.0",
    "aws-sdk": "^2.326.0",
    "request": "^2.81.0",
    "lodash": "^4.17.11"
  }
}

Credits

Nino Guba

Nino Guba

1 project • 1 follower
Thanks to LEGO MINDSTORMS Voice Challenge and Amazon Digital Services LLC.

Comments