Hackster is hosting Hackster Holidays, Ep. 4: Livestream & Giveaway Drawing. Start streaming on Wednesday!Stream Hackster Holidays, Ep. 4 on Wednesday!
Elmar ArthoBeate Artho
Created November 17, 2019

Pepper the dog

Have you always wanted a dog? Here is Pepper: You can hug and pet him. He listens, barks and smiles.. but you don't have to walk him.

AdvancedFull instructions provided5 hours164

Things used in this project

Hardware components

Lego Mindstorm Ev3 Core Set 45544
×1
Echo Dot
Amazon Alexa Echo Dot
×1
Micro SD Card 8-32 gb
×1
WiFi USB adapter
×1
Laptop with Windows 10
Computer for installing software and programming your EV3 Brick
×1

Software apps and online services

balenaEtcher
A method to flash the SD card
Microsoft Visual Studio Code
ev3dev Software
To get started: https://www.ev3dev.org/docs/getting-started/
Alexa Skills Kit
Amazon Alexa Alexa Skills Kit
Alexa Voice Service
Amazon Alexa Alexa Voice Service
Alexa Gadgets Toolkit
Amazon Alexa Alexa Gadgets Toolkit

Story

Read more

Schematics

Amazon Echo <--Directives/Events--> EV3 Mindstorms

Code

Pepper the dog Python Script only (Visual Studio Code)

Python
\alexa-gadgets-mindstorms-PepperProject.zip
alexa-gadgets-mindstorms
folder-puppy-pepper
skill-nodejs (folder for Alexa Voice Service Skills)
mission-puppy-pepper.py (code)
mission-puppy-pepper.ini (gadget id and secret)
...
unpair.sh
#!/usr/bin/env python3
# Copyright 2019 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
# adopted by Artho Family
import os
import sys
import time
import logging
import json
import random
import threading

from enum import Enum
from agt import AlexaGadget

# import required functionality 
# https://ev3dev-lang.readthedocs.io/projects/python-ev3dev/en/stable/display.html#ev3dev2.display.Display
import ev3dev2.fonts as fonts
# reference: https://ev3dev-lang.readthedocs.io/projects/python-ev3dev/en/stable/index.html
from ev3dev2.led import Leds
from ev3dev2.sound import Sound
# Motor Outputs: A: Right Leg / C: Head / D: Left Leg
from ev3dev2.motor import OUTPUT_A, OUTPUT_C, OUTPUT_D, SpeedPercent, MoveTank, LargeMotor, MediumMotor
# Sensor Inputs: 1: Touch / 4: Color
from ev3dev2.sensor import INPUT_1, INPUT_4 
from ev3dev2.sensor.lego import TouchSensor
from ev3dev2.sensor.lego import ColorSensor
from ev3dev2.display import Display
from PIL import Image
# alternative sensor: from ev3dev2.sensor.lego import InfraredSensor
# https://www.google.com/url?q=https://sites.google.com/site/ev3python/learn_ev3_python/screen&sa=D&usd=2&usg=AOvVaw0W7NpmyjCwLHXGdxvsJ1di

# 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 Command(Enum):
    """
    The list of preset commands and their invocation variation.
    These variations correspond to the skill slot values defined in ALEXA SKILLS.
    """
    LOG_COMMAND = ['log']
    BLINK_COMMAND = ['blink']
    BEEP_COMMAND = ['beep'] 
    BARK_COMMAND = ['bark'] 
    STRETCH_COMMAND = ['stretch', 'wake up'] 
    PEE_COMMAND = ['pee', 'look there is a tree','a tree to pee']
    STANDUP_COMMAND = ['stand up']
    SITDOWN_COMMAND = ['sit down']

class MindstormsGadget(AlexaGadget):
    """
    A Mindstorms gadget that performs movement based on voice commands.
    Two types of commands are supported, directional movement and preset.
    """
    class_attr_is_stand_up = 1 # class attribute (0 = sitting  <> 1 = standing)

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

        # Robot state touchsensor
        self.touchsensor = True

        # Ev3dev initialization
        self.leds = Leds()
        self.sound = Sound()
        self.drive = MoveTank(OUTPUT_A, OUTPUT_D)
        self.head = MediumMotor(OUTPUT_C)
        self.touchsensor = TouchSensor(INPUT_1)
        self.colorsensor = ColorSensor(INPUT_4)
        self.left_motor = LargeMotor(OUTPUT_D)
        self.right_motor = LargeMotor(OUTPUT_A)
        self.lcd = Display() # previously "Screen" instead of "Display"
        # alternative sensor: self.ir = InfraredSensor()

        # Start thread to monitor Touch Sensor
        threading.Thread(target=self._touchsensor_thread, daemon=True).start()
        # DEBUG ONLY logger.info("tread started..")

        # eyes of pepper at start 'hurt' (not happy ..or "tired")        
        logoHurt = Image.open('Hurt.bmp')
        self.lcd.image.paste(logoHurt, (0,0))
        self.lcd.update()
        time.sleep(5)
        # DEBUG ONLY logger.info("Pepper initialized..")

    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")
        # DEBUG ONLY: logger.info("Pepper with id {} 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")
        # DEBUG ONLY: logger.info("Pepper with id {} 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"))
            # DEBUG ONLY: print("Control payload: {}".format(payload), file=sys.stderr)
            control_type = payload["type"]

            if control_type == "command":
                # Expected params: [command]
                self._activate(payload["command"])

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



    def _activate(self, command, speed=50):
        """
        Handles preset commands.
        :param command: the preset command
        :param speed: the speed if applicable
        """
        # DEBUG ONLY: print("Activate command: ({}, {})".format(command, speed), file=sys.stderr)

        if command in Command.LOG_COMMAND.value:
            logger.info("Command received is {}!".format(command))

        # Blink in all colors available: 'RED', 'GREEN', 'YELLOW', 'ORANGE, 'AMBER', 'BLACK'(off)
        # DEBUG ONLY:  logger.info('I blink in all colors I know... and will keep the color AMBER')
        if command in Command.BLINK_COMMAND.value:
            self.leds.set_color("LEFT", "RED")
            self.leds.set_color("RIGHT", "GREEN") 
            time.sleep(1)
            self.leds.set_color("LEFT", "GREEN")
            self.leds.set_color("RIGHT", "YELLOW") 
            time.sleep(1)
            self.leds.set_color("LEFT", "YELLOW")
            self.leds.set_color("RIGHT", "ORANGE") 
            time.sleep(1)
            self.leds.set_color("LEFT", "ORANGE")
            self.leds.set_color("RIGHT", "AMBER") 
            time.sleep(1)
            self.leds.set_color("LEFT", "AMBER")
            self.leds.set_color("RIGHT", "BLACK") 
            time.sleep(1)
            self.leds.set_color("LEFT", "BLACK")
            self.leds.set_color("RIGHT", "AMBER") 
            time.sleep(1)
            self.leds.set_color("LEFT", "AMBER")
            self.leds.set_color("RIGHT", "AMBER") 

        if command in Command.BEEP_COMMAND.value:
            # DEBUG ONLY: logger.info("I beep...")
            self.sound.play_song((('C4', 'e'), ('D4', 'e'), ('E5', 'q')))

        if command in Command.BARK_COMMAND.value:
            # DEBUG ONLY: logger.info("I bark...")
            self.sound.play_file('puppy_bark.wav')

        if command in Command.STRETCH_COMMAND.value:
            # DEBUG ONLY: logger.info("I wake up and stretch myself first...")
            # -> stand up if not already standing
            is_blocking = True
            is_break =  True
            if self.class_attr_is_stand_up == 0:
                # DEBUG ONLY logger.info("I stand up")
                degree = 25
                speed = 5 # default = 50
                time.sleep(1)
                # DEBUG ONLY self.lcd.draw.text((10,10), 'Hello World .. I stand up!', font=fonts.load('luBS14'))
                # > block UP
                # self.drive.on_for_seconds(SpeedPercent(-speed), SpeedPercent(-speed), duration, block=is_blocking)
                self.drive.on_for_degrees(SpeedPercent(-speed), SpeedPercent(-speed), degree, brake=is_break,block=is_blocking)
                degree = 40
                speed = 2 # default = 50
                self.drive.on_for_degrees(SpeedPercent(-speed), SpeedPercent(-speed), degree, brake=is_break,block=is_blocking)
                time.sleep(0.1)                
                self.left_motor.COMMAND_RESET 
                self.right_motor.COMMAND_RESET
                self.class_attr_is_stand_up = 1
            # stretch
            degree = 100
            speed = 3 # default = 50
            self.drive.on_for_degrees(SpeedPercent(-speed), SpeedPercent(-speed), degree, brake=is_break,block=is_blocking)
            self.sound.play_file('Howl.wav') # puppy_stretch.wav
            time.sleep(1)
            self.drive.on_for_degrees(SpeedPercent(-speed), SpeedPercent(-speed), -degree, brake=is_break,block=is_blocking)

        if command in Command.PEE_COMMAND.value:
            # DEBUG ONLY logger.info("I stand up")
            is_blocking = True
            is_break =  True
            degree = 65
            speed = 15 # default = 50
            if self.class_attr_is_stand_up == 0:
                # DEBUG ONLY self.lcd.draw.text((10,10), 'Hello World .. I stand up!', font=fonts.load('luBS14'))
                self.drive.on_for_degrees(SpeedPercent(-speed), SpeedPercent(-speed), degree, brake=is_break,block=is_blocking)
                time.sleep(0.1)
                self.left_motor.COMMAND_RESET 
                self.right_motor.COMMAND_RESET
                self.class_attr_is_stand_up = 1 
            # Pepper is now standing -> lift his left leg (left_motor) to pee
            # logger.info("I need a break...")
            self.left_motor.on_for_degrees(speed, -1.5*degree)
            # on_for_degrees(0, SpeedPercent(-speed), degree, brake=is_break,block=is_blocking)
            time.sleep(1)
            self.sound.play_file('puppy_pee.wav')
            # self.drive.on_for_degrees(0, SpeedPercent(speed), degree, brake=is_break,block=is_blocking)
            self.left_motor.on_for_degrees(+speed*5, degree/2)
            self.left_motor.on_for_degrees(+speed*5, -degree/2)
            self.left_motor.on_for_degrees(+speed*5, degree/2)
            self.left_motor.on_for_degrees(+speed*5, -degree/2)
            self.left_motor.on_for_degrees(speed, 1.5*degree)

        if command in Command.STANDUP_COMMAND.value:
            if self.class_attr_is_stand_up == 0:
                # DEBUG ONLY logger.info("I stand up")
                is_blocking = True
                is_break =  True
                degree = 25
                speed = 5 # default = 50
                time.sleep(1)
                # DEBUG ONLY self.lcd.draw.text((10,10), 'Hello World .. I stand up!', font=fonts.load('luBS14'))
                self.drive.on_for_degrees(SpeedPercent(-speed), SpeedPercent(-speed), degree, brake=is_break,block=is_blocking)
                degree = 40
                speed = 2 # default = 50
                self.drive.on_for_degrees(SpeedPercent(-speed), SpeedPercent(-speed), degree, brake=is_break,block=is_blocking)
                time.sleep(0.1)                
                self.left_motor.COMMAND_RESET 
                self.right_motor.COMMAND_RESET
                self.class_attr_is_stand_up = 1

        if command in Command.SITDOWN_COMMAND.value:
            # only sit down if not already sitting
            if self.class_attr_is_stand_up ==  1:
                # DEBUG ONLY logger.info("I sit down")
                is_blocking = True
                is_break =  True
                degree = -65
                speed = 15 # default = 50
                self.drive.on_for_degrees(SpeedPercent(-speed), SpeedPercent(-speed), degree, brake=is_break,block=is_blocking)
                time.sleep(0.1)
                self.left_motor.COMMAND_RESET 
                self.right_motor.COMMAND_RESET
                self.class_attr_is_stand_up = 0
            # Pepper is now sitting
            # DEBUG ONLY: else:
                # DEBUG ONLY: logger.info("already sitting")

    def _touchsensor_thread(self):
        """
        Monitors if the touchsensor has been pressed (Pepper pet).
        """
        # DEBUG ONLY: logger.info("The touch sensor initialized!")
        # when Pepper is pet: his eyes will be 2 hearts (Love.bmp) and then he winks with 1 eye
        while True:
            if self.touchsensor.is_pressed: # wait_for_bump()
                # DEBUG ONLY logger.info("The touch sensor is_pressed!")
                self.leds.set_color("LEFT", "GREEN")
                self.leds.set_color("RIGHT", "GREEN")
                time.sleep(1)
                logoLove = Image.open('Love.bmp')
                self.sound.play_file('puppy_bark.wav')
                logoWinking = Image.open('Winking.bmp')
                logoNeutral = Image.open('Neutral.bmp')
                self.lcd.image.paste(logoLove, (0,0))
                self.lcd.update()
                time.sleep(4) # time to admire image
                # https://sites.google.com/site/ev3python/learn_ev3_python/screen  
                self.lcd.image.paste(logoWinking, (0,0))
                self.lcd.update()
                time.sleep(2)
                self.lcd.image.paste(logoNeutral, (0,0))
                self.lcd.update()
                time.sleep(5)
            else:
                # DEBUG ONLY logger.info("The touch sensor is_pressed!")
                self.leds.set_color("LEFT", "RED")
                self.leds.set_color("RIGHT", "RED")       

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")

    # 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")

Pepper the dog complete project ZIP (Visual Studio Code)

Python
\alexa-gadgets-mindstorms-PepperProject.zip
alexa-gadgets-mindstorms
folder-puppy-pepper
skill-nodejs (folder for Alexa Voice Service Skills)
mission-puppy-pepper.py (code)
mission-puppy-pepper.ini (gadget id and secret)
...
unpair.sh
No preview (download only).

Pepper the dog - INI Template

Python
# 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.

[GadgetSettings]
amazonId = YOUR_GADGET_AMAZON_ID
alexaGadgetSecret = YOUR_GADGET_SECRET

[GadgetCapabilities]
Custom.Mindstorms.Gadget = 1.0

Pepper the dog model.json - Alexa Voice Service SkillNodeJS

JavaScript
{
    "interactionModel": {
        "languageModel": {
            "invocationName": "mindstorms",
            "intents": [
                {
                    "name": "AMAZON.CancelIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.HelpIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.StopIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.NavigateHomeIntent",
                    "samples": []
                },
                {
                    "name": "SetCommandIntent",
                    "slots": [
                        {
                            "name": "Command",
                            "type": "CommandType"
                        }
                    ],
                    "samples": [
                        "start {Command}",
                        "pepper {Command}",
                        "puppy {Command}",
                        "activate {Command}"
                    ]
                }
            ],
            "types": [
                {
                    "name": "CommandType",
                    "values": [
                        {
                            "name": {
                                "value": "log"
                            }
                        },
                        {
                            "name": {
                                "value": "blink"
                            }
                        },
                        {
                            "name": {
                                "value": "beep"
                            }
                        },
                        {
                            "name": {
                                "value": "bark"
                            }
                        },
                        {
                            "name": {
                                "value": "stretch"
                            }
                        },
                        {
                            "name": {
                                "value": "wake up"
                            }
                        },
                        {
                            "name": {
                                "value": "pee"
                            }
                        },
                        {
                            "name": {
                                "value": "you can pee"
                            }
                        },
                        {
                            "name": {
                                "value": "look there is a tree"
                            }
                        },
                        {
                            "name": {
                                "value": "stand up"
                            }
                        },
                        {
                            "name": {
                                "value": "sit down"
                            }
                        }
                    ]
                }
            ]
        }
    }
}

Pepper the dog lambda - common.js - Alexa Voice Service SkillNodeJS

JavaScript
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
* adopted by Artho Family
*/

'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 hello to me! How can I help?';

        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');
    },
    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, 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
    };

Pepper the dog lambda - index.js - Alexa Voice Service SkillNodeJS

JavaScript
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
* adopted by Artho Family
*/

// This sample demonstrates sending directives to an Echo connected gadget from an Alexa skill
// using the Alexa Skills Kit SDK (v2). Please visit https://alexa.design/cookbook for additional
// examples on implementing slots, dialog management, session persistence, api calls, and more.

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

// 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 LaunchRequestHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest';
    },
    handle: async function(handlerInput) {

        let request = handlerInput.requestEnvelope;
        let { apiEndpoint, apiAccessToken } = request.context.System;
        let apiResponse = await Util.getConnectedEndpoints(apiEndpoint, apiAccessToken);
        if ((apiResponse.endpoints || []).length === 0) {
            return handlerInput.responseBuilder
            .speak(`Pepper not connected to Echo device.`)
            .getResponse();
        }

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

        return handlerInput.responseBuilder
            .speak("Hi my name is pepper")
            .reprompt("any news")
            .getResponse();
    }
};

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

        // Bound speed to (1-100)
        let speed = Alexa.getSlotValue(handlerInput.requestEnvelope, 'Speed');
        speed = Math.max(1, Math.min(100, parseInt(speed)));
        Util.putSessionAttribute(handlerInput, 'speed', speed);

        return handlerInput.responseBuilder
            .speak(`speed set to ${speed} percent.`)
            .reprompt("awaiting command")
            .getResponse();
    }
};

// Construct and send a custom directive to the connected gadget with
// data from the MoveIntent request.
const MoveIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'MoveIntent';
    },
    handle: function (handlerInput) {
        const request = handlerInput.requestEnvelope;
        const direction = Alexa.getSlotValue(request, 'Direction');

        // Duration is optional, use default if not available
        const duration = Alexa.getSlotValue(request, 'Duration') || "2";

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

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

        const speechOutput = (direction === "brake")
            ?  "Applying brake"
            : `${direction} ${duration} seconds at ${speed} percent speed`;

        return handlerInput.responseBuilder
            .speak(speechOutput)
            .reprompt("awaiting command")
            .addDirective(directive)
            .getResponse();
    }
};

// Construct and send a custom directive to the connected gadget with data from
// the SetCommandIntent request.
const SetCommandIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'SetCommandIntent';
    },
    handle: function (handlerInput) {

        let command = Alexa.getSlotValue(handlerInput.requestEnvelope, 'Command');
        if (!command) {
            return handlerInput.responseBuilder
                .speak("Excuse me?")
                .reprompt("Please repeat?").getResponse();
        }

        const attributesManager = handlerInput.attributesManager;
        let endpointId = attributesManager.getSessionAttributes().endpointId || [];
        let speed = attributesManager.getSessionAttributes().speed || "50";

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

        return handlerInput.responseBuilder
            .speak(`command ${command} activated`)
            .reprompt("awaiting command")
            .addDirective(directive)
            .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,
        SetSpeedIntentHandler,
        SetCommandIntentHandler,
        MoveIntentHandler,
        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();

Pepper the dog lambda - package.json - Alexa Voice Service SkillNodeJS

JSON
{
  "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"
  }
}

Pepper the dog lambda - util.js - Alexa Voice Service SkillNodeJS

JavaScript
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
* adopted by Artho Family
*/

'use strict';

const Https = require('https');

/**
 * 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();
    }));
};

Credits

Elmar Artho

Elmar Artho

1 project • 2 followers
AI early bird: developed a program for digit recognition inclusive hardware in 1988 and won the European Union Contest for Young Scientists
Beate Artho

Beate Artho

0 projects • 0 followers

Comments