The Wayback Machine - https://web.archive.org/web/20161205134146/http://docs.aws.amazon.com:80/iot/latest/developerguide/iot-lambda-rule.html
Menu
AWS IoT
Developer Guide

Creating a Lambda Rule

You can define a rule that calls a Lambda function, passing in data from the MQTT message that triggered the rule. This allows you to process the incoming message and then call another AWS or third-party service.

In this tutorial, we assume you have completed the AWS IoT Getting Started Tutorial in which you create and subscribe to an Amazon SNS topic using your cell phone number. You will create a Lambda function that publishes a message to the Amazon SNS topic you created in the AWS IoT Getting Started Tutorial. You will also create a Lambda rule that calls the Lambda function, passing in some data from the MQTT message that triggered the rule.

In this tutorial, we also assume you are using an AWS IoT button to trigger the Lambda rule. If you do not have an AWS IoT button, you can purchase one here or you can use an MQTT client to send an MQTT message that will trigger the rule.

Create the Lambda Function

To create the Lambda function:

  1. In the AWS Lambda console, choose Create a Lambda function.

    Image
  2. For the filter, type hello-world, and then choose the hello-world blueprint.

    Image
  3. On the Configure triggers page, select the box to the left of the Lambda icon, and select AWS IoT from the drop down menu.

    Image
  4. On the Configure triggers page enter your button's device serial number (DSN). Your DSN is printed on the back of your AWS IoT button. If you have not already generated a certificate and private key for your AWS IoT button, select Generate certificate and keys. Otherwise, skip to step 6.

    Image
  5. Select the links to download your certificate PEM and private key. Save these files in a secure location on your computer.

    Image

    Follow the instructions on the screen to configure your AWS IoT button.

  6. Ensure that the Enable trigger checkbox is selected and select Next.

    Image
  7. On the Configure function page, type a name and description for the Lambda function. In Runtime, choose Node.js 4.3.

    Image
  8. Scroll down to the Lambda function code section of the page. Replace the existing code with the following:

    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);
            
            // Crewate 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 
            var params = {
                Message: messageText,
                TopicArn: "arn:aws:sns:us-east-1:123456789012:MyIoTButtonSNSTopic"
             };
             sns.publish(params, context.done);
        };
  9. Scroll down to the Lambda function handler and role section of the page. For Role, choose Create a custom role. The IAM console will open, allowing you to create an IAM role that Lambda can assume when executing the Lambda function.

    To edit the role's policy to give it permission to publish to your Amazon SNS topic:

    1. Choose View Policy Document.

      Image

      Choose Edit to edit the role's policy.

      Image
    2. Replace the policy document with the following:

      {
          "Version": "2012-10-17",
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": [
                      "logs:CreateLogGroup",
                      "logs:CreateLogStream",
                      "logs:PutLogEvents"
                  ],
                  "Resource": "arn:aws:logs:*:*:*"
              },
              {
                  "Effect": "Allow",
                  "Action": [
                      "sns:Publish"
                  ],
                  "Resource": "arn:aws:sns:us-east-1:123456789012:MyIoTButtonSNSTopic"
              }
          ]
      }

      This policy document adds permission to publish to your Amazon SNS topic.

      Note

      This example uses a fictitious AWS account number in the resource ARN. Make sure to use the ARN for your Amazon SNS topic.

  10. Choose Allow.

    Image
  11. Leave the settings on the Advanced settings page at their defaults, and choose Next

    Image
  12. On the Review page, choose Create function.

    Image

Test Your Lambda Function

To test the Lambda function:

  1. From the Actions menu, choose Configure test event.

    Image
  2. Copy and paste the following JSON into the Input test event page, and then choose Save and test.

    Image
  3. In the AWS Lambda console and scroll to the bottom of the screen. The Log output section displays the output the Lambda function has written to the console.

    Image

Creating a Lambda Rule

Now that you have created a Lambda function, you can create a rule that invokes the Lambda function.

  1. In the AWS IoT console, choose Create a resource.

  2. Choose Create a rule.

  3. Type a name and description for the rule.

    Image
  4. Enter the following settings for the rule:

    Image
  5. For Choose an action, choose Insert this message into a code function and execute it (Lambda).

  6. From Function name, choose your Lambda function name, and then choose Add action.

    Image
  7. Choose Create to create your Lambda function.

    Image

Test Your Lambda Rule

In this tutorial, we assume you have completed the AWS IoT Getting Started Tutorial, which covers:

  • Configuring an AWS IoT button.

  • Creating and subscribing to an Amazon SNS topic with a cell phone number.

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), and the battery voltage.

The message should look like the following:

IOT BUTTON> {
    "serialNumber" : "ABCDEFG12345",
    "clickType" : "SINGLE",
    "batteryVoltage" : "2000 mV"
}

If you do not have a button, you can buy one here or you can use the AWS IoT MQTT client instead.

  1. In the AWS IoT console, choose MQTT Client.

    Image
  2. Type a client ID or choose Generate client ID, and then choose Connect.

    Image
  3. Choose Publish to topic.

  4. In Publish topic, type iotbutton/ABCDEFG12345.

  5. In Payload, type the following JSON, and then choose Publish.

    {
        "serialNumber" : "ABCDEFG12345",
        "clickType" : "SINGLE",
        "batteryVoltage" : "2000 mV"
    }

    Image

    You should receive a message on your cell phone.

Image