Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Publish mqtt message to topic from aws lambda using aws iot

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?

like image 990
Abdul Manaf Avatar asked Oct 13 '16 14:10

Abdul Manaf


2 Answers

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.

like image 170
Abdul Manaf Avatar answered Sep 20 '22 13:09

Abdul Manaf


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"); });

like image 21
lennartcl Avatar answered Sep 17 '22 13:09

lennartcl