6

I need to publish data from aws lambda through mqtt protocol using aws iot. i have created a lambda function with node.js code. like this

exports.handler = (event, context, callback) => {

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

    var device = awsIot.device({
        keyPath: 'samplepath/test.pem.key',
        certPath: 'samplepath/test.crt',
        caPath: 'samplepath',
        clientId: 'sampleId',
        region: 'us-east-1'
    });

    device
        .on('connect', function () {
            console.log('connected');
            device.publish('test_topic', JSON.stringify({ "test_name": "hello", "test_value": 1001 }));
            console.log('published successfully');
            callback(null, 'item added');
        });
}

I got mqtt message on subscriber. but lambda produce error message like this

Task timed out after 10.00 seconds 

I have used context.succeed() instead of callback, lambda is exited properly. i cant get any messages on subscriber.

In both cases console prints published successfully message properly.

What is the issue related with my publishing code?

4

2 回答 2

3

我了解我的 lambda 函数在连接到 AWS IoT 时超时。关于我们正在使用的 sdk,aws-iot-device-sdk 旨在在嵌入式设备内部使用。当我们使用 Lambda 函数或尝试在计算机中发布时,最佳实践是使用 aws-sdk。使用 aws-sdk 我们不需要使用证书在 AWS IoT 中发布,我们只需使用 AWS 凭证来执行此操作。此外,借助 aws-sdk,我们可以在 IoT 中执行管理任务,我们可以创建事物、创建证书等。

来到我的代码,函数没有结束和超时的原因是回调必须等待异步调用完成执行,我认为这是通过从函数到物联网保持连接来帮助的。context.succeed() 正确退出但我们没有收到任何消息的原因一定是因为 context.succeed 没有等待我们的异步调用完成执行。

于 2016-10-14T11:07:32.690 回答
2

确保在发布消息后断开与设备的连接,否则 Lambda 将在连接保持活动状态时等待(请参阅http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context. html , 寻找callbackWaitsForEmptyEventLoop).

要在完成后断开连接,只需更改callback(null, 'item added');

device.end((err) => { callback(err, "item added"); });

于 2017-01-04T11:01:51.873 回答