Post a mqtt post on a topic from aws lambda using aws iot

I need to publish data from aws lambda via the mqtt protocol using aws iot. I 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 received the mqtt message on the subscriber. but lambda produces an error message like this

 Task timed out after 10.00 seconds 

I used context.succeed () instead of a callback, lambda exited properly. I can’t get any messages on the subscriber.

In both cases, deleted messages are successfully published successfully.

What is the problem with my post code?

+5
source share
2 answers

I understand that my lambda function is disabled when connected to AWS IoT. About the sdk used, aws-iot-device-sdk is intended to be used inside an embedded device. When we use the lambda function or try to publish to a computer, the best practice is to use the AWS-SDK. Using aws-sdk, we don’t need to use certificates to publish to AWS IoT, we just use AWS credentials for this. In addition, with aws-sdk we can perform administrative tasks in IoT, we can create a thing, create a certificate, etc.

Approaching my code, the reason the function does not end and the time because the callback must wait for the asynchronous call to complete execution, which, I believe, helps in the connection, is supported from function to IoT. The reason context.succeed () failed, but we did not receive any messages. because context.succeed does not wait for the completion of our asynchronous calls.

+3
source

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

To disconnect when everything is done, just change callback(null, 'item added'); on the

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

+2
source

Source: https://habr.com/ru/post/1258151/


All Articles