Codementor Events

NodeJs Connect AWS-IOT Device with JS SDK Part-2

Published May 30, 2018Last updated Nov 26, 2018
NodeJs Connect AWS-IOT Device with JS SDK Part-2

Now ,we have some Idea how AWS-IOT work and how we can implement with nodejs as we saw in previous part.Here we are going to create lambda function that will invoke from the rule which is trigger on AWS-IOT Button click and lambda will publish SNS to your mobile number in a simplest way.
You can check Part1 here

Create the Lambda Function
To create the Lambda function:
In the AWS Lambda console, choose Get Started Now or, if you have created a Lambda function before, choose Create a Lambda function.I have function named myButton which looks like

console.log('Loading function');
    // Load the AWS SDK
    var AWS = require("aws-sdk");
    
    // Set up the code to call when the Lambda function is invoked
    exports.handler = (event, context, callback) => {
        // Load the message passed into the Lambda function into a JSON object 
        var eventText = JSON.stringify(event, null, 2);
        
        // Log a message to the console, you can view this text in the Monitoring tab in the Lambda console or in the CloudWatch Logs console
        console.log("Received event:", eventText);
        
        // Create a string extracting the click type and serial number from the message sent by the AWS IoT button
        var messageText = "Received  " + event.clickType + " message from button ID: " + event.serialNumber;
        
        // Write the string to the console
        console.log("Message to send: " + messageText);
        
        // Create an SNS object
        var sns = new AWS.SNS();
        
        // Populate the parameters for the publish operation
        // - Message : the text of the message to send
        // - TopicArn : the ARN of the Amazon SNS topic to which you want to publish 
        const param = {
           TopicArn: arn:aws:sns:us-west-2:123456789012:test-topic1,
           Message: messageText,
        };
        SNS.publish(param, function (err, data) {
            if (err){
              console.log(err); // an error occurred
            }else{
                console.log(data);
            }           // successful response
        });
    };

Here i am using Topic because you can subscribe to multiple numbers on same topic and it will send notification to all subscribed number.So lets create Topic and subcribe some Phone numbers.You can do either programmaticaly or AWS https://docs.aws.amazon.com/iot/latest/developerguide/iot-lambda-rule.html, as i used to create topic from my application side like this:

            SNS.createTopic({Name: _topicName}, (err, data) => {
                if (err) {
                    cb(err, null)
                } else {
                    _topicArn = data.TopicArn;
                }
              });

Now Subscibe some numbers using above topic:

    var _subScribeToTopic = function (cb) {
        //Subscribe to all given numbers
        var _phoneNumber = ['+91XXXXXXXXXXX','+91YYYYYYYYYYY','+91ZZZZZZZZZZZZ']
        _phoneNumber.forEach(function (number, index) {
            var params = {
                Protocol: 'sms', /* required */
                TopicArn: _topicArn, /* required */
                Endpoint: number   //Phone number to send sns
            };
            SNS.subscribe(params, function (err, data) {
                if (err) {
                    cb(err, null); // an error occurred   
                } else {
                    cb(null, data); // successful response   
                }
           });
        });
    }

LAMBDA RULE
So , we subscribed our numbers with the topic.Next we have to create the rule to invoke Lambda function to send sms to phone.For that goto AWS IOT Console and navigate to ACT and On the Rules page, choose Create and Type a name and description for the rule.
1.Enter the following settings for the rule:
lambda-rule-settings-1.png

2.In Set one or more actions, choose Add action.
3.On the Select an action page, select Invoke a Lambda function passing the message data, and then choose Configure action.
4.From the Function name drop-down list, choose your Lambda function name, then choose Add action.
5.Choose Create rule to create your Lambda function.

Now that your button is configured and connected to Wi-Fi and you have configured an Amazon SNS topic, you can press the button to test your Lambda rule. You should receive an SMS text message on your phone that contains:
The serial number of your button.
The type of button press (SINGLE or DOUBLE).
The battery voltage.

We are done 🙌. You can find the files and code onGithub.

Discover and read more posts from Mohammed AbdurRaheem
get started
post commentsBe the first to share your opinion
Show more replies