AWS Lambda Node JS和Alexa技能套件

问题描述

在Alexa Skill kit中进行测试时,有时响应与最后一个响应相同,例如,如果我说打开灯,则表明光正在关闭,或者如果我说关闭灯,则表明其正在打开。基本上我也使用AWS IoT控制RaspBerry Pi的LED,但目前我正面临这个问题。我在lambda上部署的Node js代码如下。

var awsIot = require('aws-iot-device-sdk');

var host = "my host";
var topic = "$aws/things/lights/shadow/update";
var app_id = "my skill";
var deviceName = "lights";

var mqtt_config = {
    "keyPath": "./certs/private.pem.key","certPath": "./certs/cert.pem.crt","caPath": "./certs/AmazonRootCA1.key","host": host,"port": 8883,"clientId": deviceName,"region":"eu-west-1","debug":true
};

var ctx = null;
var client = null;

// Route the incoming request based on type (LaunchRequest,IntentRequest,etc.) The JSON body of the request is provided in the event parameter.
exports.handler = function (event,context) {
    try {
        console.log("event.session.application.applicationId=" + event.session.application.applicationId);
        ctx = context;

        if (event.session.application.applicationId !== app_id) {
             ctx.fail("Invalid Application ID");
         }

        client = awsIot.device(mqtt_config);

        client.on("connect",function(){
            console.log("Connected to AWS IoT");
        });


        if (event.session.new) {
            onSessionStarted({requestId: event.request.requestId},event.session);
        }

        if (event.request.type === "LaunchRequest") {
            onLaunch(event.request,event.session);
        }  else if (event.request.type === "IntentRequest") {
            onIntent(event.request,event.session);
        } else if (event.request.type === "SessionEndedRequest") {
            onSessionEnded(event.request,event.session);
            ctx.succeed();
        }
    } catch (e) {
        console.log("EXCEPTION in handler:  " + e);
        ctx.fail("Exception: " + e);
    }
};

/**
 * This function called when the session starts.
 */
function onSessionStarted(sessionStartedRequest,session) {
    console.log("onSessionStarted requestId=" + sessionStartedRequest.requestId + ",sessionId=" + session.sessionId);
}


/**
 *This function called when the user launches the skill
 */
function onLaunch(launchRequest,session,callback) {
    console.log("onLaunch requestId=" + launchRequest.requestId + ",sessionId=" + session.sessionId);

    // dispatch to your skill's launch.
    getWelcomeResponse(callback);
}

/**
 * This function called when the user specifies an intent for this skill.
 */
function onIntent(intentRequest,session ) {
    console.log("onIntent requestId=" + intentRequest.requestId + ",sessionId=" + session.sessionId);

    var intent = intentRequest.intent,intentName = intentRequest.intent.name;

    console.log("REQUEST to string =" + JSON.stringify(intentRequest));

    var callback = null;
    // dispatch to your skill's intent handlers
    if ("LightIntent" === intentName) {
        lightIntent(intent,session);
    }
     else if ("LightIntentOff" === intentName){
         lightIntentOff(intent,session);
         
     }
     else if("RoomLightIntent" === intentName)
     {
         roomLightIntent(intent,session);
     }
     
     else 
     {
        throw "Invalid intent";
    }
}

/**
 * This function called when the user ends the session.
 */
function onSessionEnded(sessionEndedRequest,session) {
    console.log("onSessionEnded requestId=" + sessionEndedRequest.requestId + ",sessionId=" + session.sessionId);
}

// --------------- Functions that control the skill's behavior -----------------------

function getWelcomeResponse() {
    // If we wanted to initialize the session to have some attributes we Could add those here.
    var sessionAttributes = {};
    var cardTitle = "Welcome";
    var speechOutput = "Welcome to the Smart Caravan";

    var repromptText = "Please tell hymer assistant your command.";
    var shouldEndSession = false;

    ctx.succeed(buildresponse(sessionAttributes,buildSpeechletResponse(cardTitle,speechOutput,repromptText,shouldEndSession)));
}

function lightIntent(intent,callback) {
    var repromptText = null;
    var sessionAttributes = {};
    var shouldEndSession = false;
    var speechOutput = "";

    repromptText = "Hope,the lights are on";

    var task = intent.slots.Task.value;
    var validTasks = ["turn on light","turn on the light"];
    if (validTasks.indexOf(task) == -1)
    {
        speechOutput = "Couldn't understand the command -> lightIntent";
        ctx.succeed(buildresponse(sessionAttributes,shouldEndSession)));
    }
    else
    {
        var cardTitle = "Turning Lights On"  ;
        speechOutput = "Turning Lights On" ;
        mqttPublish(intent,sessionAttributes,cardTitle,shouldEndSession);
    }
}
function lightIntentOff(intent,the lights are off";

    var taskoff = intent.slots.Taskoff.value;
    var validTasksOff = ["turn off light","turn off the light"];
    if (validTasksOff.indexOf(taskoff) == -1)
    {
        speechOutput = "Couldn't understand the command -> lightIntentOff";
        ctx.succeed(buildresponse(sessionAttributes,shouldEndSession)));
    }
    else
    {
        var cardTitle = "Turning Lights Off"  ;
        speechOutput = "Turning Lights Off" ;
        mqttPublish(intent,shouldEndSession);
    }
}

function roomLightIntent(intent,the lights are on";

    var roomtask = intent.slots.RoomTask.value;
    var RoomvalidTasks = ["turn on room light","turn on the room light"];
    if (RoomvalidTasks.indexOf(roomtask) == -1)
    {
        speechOutput = "Couldn't understand the command -> roomLightIntent";
        ctx.succeed(buildresponse(sessionAttributes,shouldEndSession)));
    }
    else
    {
        var cardTitle = "Turning room Lights On"  ;
        speechOutput = "Turning room Lights On" ;
        mqttPublish(intent,shouldEndSession);
    }
}

function mqttPublish(intent,shouldEndSession)
{
    var strIntent = JSON.stringify(intent);
    console.log("mqttPublish:  INTENT text = " + strIntent);

    client.publish(topic,strIntent,function() {
        client.end();
    });

    client.on("close",(function () {
        console.log("MQTT CLIENT CLOSE - successfully. ");
        ctx.succeed(buildresponse(sessionAttributes,shouldEndSession)));
    }));

    client.on("error",(function (err,granted) {
        console.log("MQTT CLIENT ERROR!!  " + err);
    }));
}


// --------------- Helpers that build all of the responses -----------------------

function buildSpeechletResponse(title,output,shouldEndSession) {
    return {
        outputSpeech: {
            type: "PlainText",text: output
        },card: {
            type: "Simple",title: title,content: output
        },reprompt: {
            outputSpeech: {
                type: "PlainText",text: repromptText
            }
        },shouldEndSession: shouldEndSession
    };
}

function buildresponse(sessionAttributes,speechletResponse) {
    return {
        version: "1.0",sessionAttributes: sessionAttributes,response: speechletResponse
    };
}

Alexa Skill kit JSON如下。我有三个意图,分别具有不同的插槽和三种插槽类型。

{
    "interactionModel": {
        "languageModel": {
            "invocationName": "hymer assistant","modelConfiguration": {
                "fallbackIntentSensitivity": {
                    "level": "LOW"
                }
            },"intents": [
                {
                    "name": "AMAZON.FallbackIntent","samples": []
                },{
                    "name": "AMAZON.CancelIntent",{
                    "name": "AMAZON.HelpIntent",{
                    "name": "AMAZON.StopIntent",{
                    "name": "AMAZON.NavigateHomeIntent",{
                    "name": "AMAZON.MoreIntent",{
                    "name": "AMAZON.NavigateSettingsIntent",{
                    "name": "AMAZON.NextIntent",{
                    "name": "AMAZON.PageUpIntent",{
                    "name": "AMAZON.PageDownIntent",{
                    "name": "AMAZON.PrevIoUsIntent",{
                    "name": "AMAZON.ScrollRightIntent",{
                    "name": "AMAZON.ScrollDownIntent",{
                    "name": "AMAZON.ScrollLeftIntent",{
                    "name": "AMAZON.ScrollUpIntent",{
                    "name": "LightIntent","slots": [
                        {
                            "name": "Task","type": "LIST_OF_TASKS"
                        }
                    ],"samples": [
                        "{Task}"
                    ]
                },{
                    "name": "LightIntentOff","slots": [
                        {
                            "name": "Taskoff","type": "LIST_TASKS_OFF"
                        }
                    ],"samples": [
                        "{Taskoff}"
                    ]
                },{
                    "name": "RoomLightIntent","slots": [
                        {
                            "name": "RoomTask","type": "LIST_ROOM_TASKS"
                        }
                    ],"samples": [
                        " {RoomTask}"
                    ]
                }
            ],"types": [
                {
                    "name": "LIST_OF_TASKS","values": [
                        {
                            "name": {
                                "value": "turn on light"
                            }
                        },{
                            "name": {
                                "value": "turn on the light"
                            }
                        }
                    ]
                },{
                    "name": "LIST_TASKS_OFF","values": [
                        {
                            "name": {
                                "value": "turn off the light"
                            }
                        },{
                            "name": {
                                "value": "turn off Light"
                            }
                        }
                    ]
                },{
                    "name": "LIST_ROOM_TASKS","values": [
                        {
                            "name": {
                                "value": "turn on the room light"
                            }
                        },{
                            "name": {
                                "value": "turn on room light"
                            }
                        }
                    ]
                }
            ]
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)