AWS Lambda无法正确发布到IoT主题

时间:2018-08-09 12:37:53

标签: node.js aws-lambda aws-iot

我已经使用JavaScript编写了Lambda函数,该函数可以响应我的声音并打开Raspberry上的LED。 但是我在将其状态发布到我的事物主题时遇到了问题。虽然Alexa回答正确(如果Im要求打开它,则为“打开”,如果要求关闭则为“关闭”),但我的主题并不总是能得到状态变化。有时它获取数据,有时却不获取数据,再经过几次调用后,它将获取大量数据,而我什至无法获得在该大量中创建数据序列的逻辑。

var AWS = require('aws-sdk');

var config = {};
config.IOT_BROKER_ENDPOINT      = "xxxxxx.iot.us-east-1.amazonaws.com";
config.IOT_BROKER_REGION        = "us-east-1";
config.IOT_THING_NAME           = "raspberry";

var iotData = new AWS.IotData({endpoint: config.IOT_BROKER_ENDPOINT});
var topic = 'LED';

exports.handler = function (event, context) {
...
...
function updatePowerState (intent, session, callback) {
    var speechOutput = '';
    var newValue = '';
    var repromptText = '';
    const cardTitle = 'Power';
    var sessionAttributes = {};
    const shouldEndSession = true;
    var value = intent.slots.PowerState.value;
    if(value == 'on' || value == 'off') {
        newValue = value.toUpperCase();
        speechOutput = 'Turning your lamp ' + value;
        updateShadow(newValue);
    } else {
        speechOutput = 'I didnt understand you. Please, repeat your request.';
    }
    callback(sessionAttributes, buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));    
}

function updateShadow(newValue) {
        let payload = {
        state: {
            desired: {
                power_state: newValue
            }
        }
    };

    var JSON_payload = JSON.stringify(payload);

    var updates = {
        topic: topic,
        payload: JSON_payload,
        qos: 0
    };

    iotData.publish(updates, (err, data) => {
  if(err) {
      console.log(err);
  }
  else {
      console.log('Success!');
  }
});
}

您对它的起因有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

iotData.publish之类的异步方法会导致AWS Lambda出现问题,因为您请求执行,并且lambda函数很快就会结束,而无需等待响应和处理请求。

另一个问题可能是您的权限。