Question:
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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
1 2 |
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?
Answer:
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.