Publish mqtt message to topic from aws lambda using aws iot
Asked Answered
N

2

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?

Nelsen answered 13/10, 2016 at 14:35 Comment(0)
N
3

I understand my lambda function is timing out when connecting to AWS IoT. About the sdk we are using, the aws-iot-device-sdk is designed to use inside of an embedded device. When we are using a Lambda function or trying to publish in a computer, the best practice is use the aws-sdk. Using the aws-sdk we don't need to use the certificates to publish in the AWS IoT, we just use the AWS credentials to do this. Also, with aws-sdk we can do administrative tasks in the IoT, we can create a thing, create a certificate, etc.

Coming to my code, the reason the function does not end and times out is because the callback must be waiting for an asynchronous call to finish execution, which I assume is being help up by the connection being maintained from the function to IoT. The reason context.succeed() exited properly but we did not get any messages must be because context.succeed does not wait for our async calls to finish execution.

Nelsen answered 14/10, 2016 at 11:7 Comment(0)
T
2

Make sure you disconnect from the device after you published the message, otherwise Lambda will wait while the connection stays alive (see http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html, look for callbackWaitsForEmptyEventLoop).

To disconnect when done, simply change callback(null, 'item added'); to

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

Torry answered 4/1, 2017 at 11:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.