我正在尝试使用Amazon Alexa,IoT和Lambda控制树莓派。到目前为止,我的工作是:
这是我的node.js脚本中的意图处理:
switch(event.request.intent.name) {
case "testone":
var config = {};
config.IOT_BROKER_ENDPOINT = "restAPILinkFromIoT".toLowerCase();
config.IOT_BROKER_REGION = "us-east-1";
//Loading AWS SDK libraries
var AWS = require('aws-sdk');
AWS.config.region = config.IOT_BROKER_REGION;
var iotData = new AWS.IotData({endpoint: config.IOT_BROKER_ENDPOINT});
var topic = "/test";
var output = "test output without publish"
var params = {
topic: topic,
payload: "foo bar baz",
qos:0
};
iotData.publish(params, (err, data) => {
if (!err){
output = "publish without error"
this.emit(':tell', tell);
} else {
output = err
}
});
context.succeed(
generateResponse(
buildSpeechletResponse(output, true),
{}
)
)
break;
...
基本上,脚本应该返回“无错误发布”或错误消息。问题总是返回“测试输出而不发布”。似乎从未触发过发布功能(或至少是回调功能)。在主题中,我也没有看到任何消息。
难道我做错了什么?
提前致谢!
这部分:
iotData.publish(params, (err, data) => {
if (!err){
output = "publish without error"
this.emit(':tell', tell);
} else {
output = err
}
});
是异步方法调用。该iotData.publish()
方法将立即返回。if(!err) ...
一旦异步调用完成,带有代码块的匿名回调函数将在以后的某个时间执行。
那意味着这部分:
context.succeed(
generateResponse(
buildSpeechletResponse(output, true),
{}
)
)
在IoTpublish()
调用完成之前,output
变量尚未分配任何值之前被调用。
要解决此问题,您可以将代码移到回调本身中:
iotData.publish(params, (err, data) => {
if (!err){
context.succeed(generateResponse(
buildSpeechletResponse("publish without error", true),
{});
)
} else {
context.succeed(generateResponse(
buildSpeechletResponse(err, true),
{});
}
});
附带说明一下,我真的不建议尝试同时学习NodeJS,AWS Lambda和IoT。如果您需要在学习Lambda和其他AWS知识的同时学习一种语言,我建议使用Python,因为您不必在Python中处理这些异步回调问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句