【问题标题】:Need help publishing to IoT topic using Lambda and node Js需要帮助使用 Lambda 和节点 Js 发布到 IoT 主题
【发布时间】:2017-11-26 18:50:55
【问题描述】:

我正在尝试使用 Amazon Alexa、IoT 和 Lambda 来控制我的树莓派。 到目前为止我的工作:

  • 将 raspberry 设置为 IoT 设备并能够发布和订阅主题(使用 IoT 客户端进行测试)
  • 设置测试 lambda node.js 脚本
  • 在我的 lambda 脚本中设置触发意图的测试 Alexa Skill

这是我的 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;
        ...

基本上,脚本应该返回“无错误发布”或错误消息。问题它总是返回“没有发布的测试输出”。似乎永远不会触发发布函数(或至少是回调函数)。我也没有在主题中看到消息。

我做错了吗?

提前致谢!

【问题讨论】:

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


    【解决方案1】:

    这部分:

       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),
                {}
              )
            )
    

    在 IoT publish() 调用完成之前以及在 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 中处理这些异步回调问题。

    【讨论】:

      猜你喜欢
      • 2018-10-01
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      • 2012-05-10
      • 2019-11-04
      相关资源
      最近更新 更多