How to Notify MQTT Messages to SNS Using AWS IoT Rules

TOC

How to Notify MQTT Messages to SNS Using AWS IoT Rules

In this article, we will explain how to use AWS IoT Rules to notify the content of MQTT messages to Amazon SNS.

The SNS (sns) action sends the data from an MQTT message as an Amazon Simple Notification Service (Amazon SNS) push notification.

SNS

This time, we will automatically construct AWS IoT Rules, SNS topics, and IAM roles using CloudFormation to create a system that sends SMS notifications when temperature data exceeds a certain threshold. This allows you to receive important information promptly and respond accordingly.

We referred to the following page:

あわせて読みたい
Tutorial: Sending an Amazon SNS notification - AWS IoT Core This tutorial demonstrates how to create an AWS IoT rule that sends MQTT message data to an Amazon SNS topic so that it can be sent as an SMS text message.

Configuration

Diagram of notifying SNS using AWS IoT rules
  • AWS IoT Rule: Notifies SNS of messages published to a specific topic.
  • IAM Role: Grants permissions for the IoT Rule to access SNS.
  • SNS Topic: Uses SMS and specifies a mobile phone number as the notification destination.

Resources

AWS IoT Rule Settings

Detail of AWS IoT 01.

We define the rule using SQL. This time, we will create a message consisting of three data points. In addition, use the FROM and WHERE clause to set the topics and conditions under which the data will be retrieved.

device_id

This data is named device_id and uses the topic function to split the topic name by slashes and retrieve the second string.

Returns the topic to which the message that triggered the rule was sent. If no parameter is specified, the entire topic is returned.

topic(Decimal)

reported_temperature

Named reported_temperature, it uses the temperature data included in the message delivered to the original topic.

max_temperature

Named max_temperature, this value is a fixed value of “30”.

FROM clause

In the FROM clause, specify the topic name from which to retrieve the data. In this configuration, we target the topic device/+/data.

WHERE clause

Using the WHERE clause, we set a condition on the data to be processed. Specifically, we target only messages where the value of temperature is greater than 30 to notify SNS.

Detail of AWS IoT 02.

As an action for SNS, specify the notification destination SNS topic, format, and IAM role. Set the format to RAW.

For the basics of AWS IoT Rules, please check the following page:

あわせて読みたい
How to Republish MQTT Messages Using AWS IoT Rules 【How to Republish MQTT Messages Using AWS IoT Rules】 AWS IoT provides a feature called AWS IoT Rules. AWS IoT rules send data from your devices to other AW...

IAM Role Settings

Detail of IAM role 02.
Detail of IAM role 01.

In the trust policy, allow the iot.amazonaws.com service to assume this IAM role. The IAM policy attached to the IAM role permits the sns:Publish action. Specify the ARN of the SNS topic as the target, allowing messages to be sent to this topic.

We referred to the following page for the necessary permissions:

あわせて読みたい
SNS - AWS IoT Core Use the SNS rule action to send an MQTT message from AWS IoT as an Amazon Simple Notification Service push notification.

SNS Topic Settings

Detail of AWS SNS 01.

Subscribe to this topic by specifying the mobile phone number and SMS protocol.

For how to notify messages via SMS, please check the following page. Note that by default, the AWS account is placed in the SMS sandbox, so messages cannot be notified to unregistered phone numbers.

あわせて読みたい
How to Send Notifications via SMS Using AWS SNS 【How to Send Notifications via SMS Using AWS SNS】 In AWS SNS (Simple Notification Service), you can choose from a variety of notification destinations. Acc...

CloudFormation Template

AWS IoT Rule

Resources:
  TopicRule:
    Type: AWS::IoT::TopicRule
    Properties:
      RuleName: temp_limit_notify
      TopicRulePayload: 
        Actions: 
          - Sns: 
              MessageFormat: RAW
              RoleArn: !GetAtt TopicRuleRole.Arn
              TargetArn: !Ref SnsTopicArn
        AwsIotSqlVersion: 2016-03-23
        RuleDisabled: false
        Sql: !Sub |
          SELECT topic(2) as device_id, 
              temperature as reported_temperature, 
              30 as max_temperature 
            FROM '${TopicName}' 
            WHERE temperature > 30
Code language: YAML (yaml)

IAM Role

Resources:
  TopicRuleRole:
    Type: AWS::IAM::Role
    DeletionPolicy: Delete
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: sts:AssumeRole
            Principal:
              Service:
                - iot.amazonaws.com
      Policies:
        - PolicyName: TopicRulePolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - sns:Publish
                Resource:
                  - !Ref SnsTopicArn
Code language: YAML (yaml)

SNS Topic

Resources:
  Topic:
    Type: AWS::SNS::Topic
    Properties:
      FifoTopic: false
      Subscription: 
        - Endpoint: !Ref PhoneNumber
          Protocol: sms
      TopicName: !Sub "${Prefix}-sns-topic"
Code language: YAML (yaml)

Full Template

GitHub
awstut-fa/160 at main · awstut-an-r/awstut-fa Contribute to awstut-an-r/awstut-fa development by creating an account on GitHub.

Verification

If the temperature is above 30

First, subscribe to the topic device/+/data.

Detail of AWS IoT 03.

Next, publish a message to the topic device/32/data.

Detail of AWS IoT 04.

You have successfully received the message on the subscribed topic. This topic uses wildcard notation and can receive the message you just published.

Looking at the value of temperature, it is “38”, which is greater than 30. Therefore, this message meets the condition of the AWS IoT Rule, and a message is sent to the SNS topic.

Detail of AWS IoT 05.

Check the SMS app on your mobile phone. Indeed, the message has been sent. Looking at the content of the message, it includes three data points: device_id, reported_temperature, and max_temperature. Each corresponds to what was specified in the SQL expression.

If the temperature is less than 30

Finally, send one more message. Publish a message to the topic device/33/data.

Detail of AWS IoT 06.

The message was successfully published. However, no short message arrived on the mobile phone. This is because the temperature value of the published message was “28”, which is less than 30. In other words, this message did not meet the condition of the AWS IoT Rule, so a message was not sent to the SNS topic.

Conclusion

We have confirmed how to use AWS IoT Rules to notify MQTT messages to Amazon SNS. By utilizing CloudFormation, we automated the settings of the SNS topic, IAM role, and IoT Rule. This mechanism allows you to receive important information in real-time and enables prompt response.

Notifying SNS using AWS IoT rules

On this page, you will see how to use AWS IoT rules to notify SNS of the contents of MQTT messages.

The SNS (sns) action sends the data from an MQTT message as an Amazon Simple Notification Service (Amazon SNS) push notification.

SNS

In this case, we will use CloudFormation to automatically build AWS IoT rules, SNS topics, and IAM roles to create a system that will notify you via SMS when temperature data exceeds certain thresholds. This will allow us to receive and respond to critical information quickly.

The following pages are used as reference for this issue.

あわせて読みたい
Tutorial: Sending an Amazon SNS notification - AWS IoT Core This tutorial demonstrates how to create an AWS IoT rule that sends MQTT message data to an Amazon SNS topic so that it can be sent as an SMS text message.

Environment

Diagram of notifying SNS using AWS IoT rules
  • AWS IoT Rules: Notify SNS of messages issued to specific topics.
  • IAM Roles: Grant permissions for IoT rules to access SNS.
  • SNS Topic: Use SMS and specify a cell phone number as the notification destination.

CloudFormation template files

The above configuration is built with CloudFormation.
The CloudFormation template is placed at the following URL

GitHub
awstut-fa/160 at main · awstut-an-r/awstut-fa Contribute to awstut-an-r/awstut-fa development by creating an account on GitHub.

Explanation of key points of template files

AWS IoT Rules

Resources:
  TopicRule:
    Type: AWS::IoT::TopicRule
    Properties:
      RuleName: temp_limit_notify
      TopicRulePayload: 
        Actions: 
          - Sns: 
              MessageFormat: RAW
              RoleArn: !GetAtt TopicRuleRole.Arn
              TargetArn: !Ref SnsTopicArn
        AwsIotSqlVersion: 2016-03-23
        RuleDisabled: false
        Sql: !Sub |
          SELECT topic(2) as device_id, 
              temperature as reported_temperature, 
              30 as max_temperature 
            FROM '${TopicName}' 
            WHERE temperature > 30
Code language: YAML (yaml)

For basic information on AWS IoT rules, please refer to the following pages.

あわせて読みたい
How to Republish MQTT Messages Using AWS IoT Rules 【How to Republish MQTT Messages Using AWS IoT Rules】 AWS IoT provides a feature called AWS IoT Rules. AWS IoT rules send data from your devices to other AW...

To send a message to an SNS, set the Sns property.

The MessageFormat property allows you to set the format of the message to be sent.
You can select either “JSON” or “RAW” for this property, and the latter is specified in this case.

The TargetArn property specifies the SNS topic to be notified.

The Sql property defines the specific rule.
In this case, we will create a message consisting of three pieces of data.

The first is data named device_id.
This data uses the second string from the following topic function, which splits the topic name with a slash.

Returns the topic to which the message that triggered the rule was sent. If no parameter is specified, the entire topic is returned.

topic(Decimal)

The second is data named reported_temperature.
This uses the temperature data contained in the message delivered to the original topic.

The third data is named max_temperature.
This value is fixed at “30”.

The FROM clause specifies the name of the topic from which to retrieve data.
In this configuration, the topic device/+/data is targeted.
The topic name is specified using CloudFormation’s built-in function Sub.

However, the WHERE clause is used to set conditions on the data to be processed.
Specifically, the SNS will be notified only when the value of temperature is greater than 30.

Below are the IAM roles for AWS IoT rules.

Resources:
  TopicRuleRole:
    Type: AWS::IAM::Role
    DeletionPolicy: Delete
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: sts:AssumeRole
            Principal:
              Service:
                - iot.amazonaws.com
      Policies:
        - PolicyName: TopicRulePolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - sns:Publish
                Resource:
                  - !Ref SnsTopicArn
Code language: YAML (yaml)

In the inline policy for the IAM role, give the SNS the necessary permissions for notification.
The required permissions are listed on the following page.

あわせて読みたい
SNS - AWS IoT Core Use the SNS rule action to send an MQTT message from AWS IoT as an Amazon Simple Notification Service push notification.

Specify this IAM role in the RoleArn property described above.

(Reference) SNS Topics

Resources:
  Topic:
    Type: AWS::SNS::Topic
    Properties:
      FifoTopic: false
      Subscription: 
        - Endpoint: !Ref PhoneNumber
          Protocol: sms
      TopicName: !Sub "${Prefix}-sns-topic"
Code language: YAML (yaml)

Set SMS as the protocol and the cell phone number as the notification destination.

For information on how to notify messages to SMS, please see the following page.

あわせて読みたい
How to Send Notifications via SMS Using AWS SNS 【How to Send Notifications via SMS Using AWS SNS】 In AWS SNS (Simple Notification Service), you can choose from a variety of notification destinations. Acc...

In particular, by default, messages cannot be notified to unregistered phone numbers because the AWS account is placed in the SMS sandbox.
Please read the page above to learn more about this.

Architecting

Use CloudFormation to build this environment and check its actual behavior.

Create CloudFormation stacks and check the resources in the stacks

Create CloudFormation stacks.
For information on how to create stacks and check each stack, please refer to the following pages.

あわせて読みたい
CloudFormation’s nested stack 【How to build an environment with a nested CloudFormation stack】 Examine nested stacks in CloudFormation. CloudFormation allows you to nest stacks. Nested ...

Check the AWS IoT rules created.

Detail of AWS IoT 01.

You can see that the SQL expression that is the body of the rule has been successfully set.
We can also see that the rule targets messages issued to the topic device/+/data.

You can also see that notifications to SNS are specified as an action.

Check the details of the notification action.

Detail of AWS IoT 02.

You can check the SNS topics, etc. to which you are notified.

Detail of AWS SNS 01.

The SNS topic has been successfully created.
When I check the device subscribing to this topic, it does indeed specify “SMS” as the protocol and a phone number as the endpoint.

Operation Check

Now that you are ready, access the MQTT test client page to check the operation.

First, subscribe to the topic device/+/data.

Detail of AWS IoT 03.

Then issue a message for the topic device/32/data.

Detail of AWS IoT 04.

The topic device/+/data allows us to receive the previous message.
This topic can receive the previous message by wildcard notation.

Looking at the temperature value, it is “38”, which is greater than 30.
This means that this message meets the requirements of the AWS IoT rule, so the message will be sent to the SNS topic.

Check the SMS application on your phone.

Detail of AWS IoT 05.

The message was indeed sent.

Looking at the content of the message, it contains three pieces of data: device_id, reported_temperature, and max_temperature.
Each is as specified in the SQL expression.

Send the message one last time.
Issue a message for the topic device/33/data.

Detail of AWS IoT 06.

The message was successfully issued.

However, no short message was received on the cell phone.
This is because the temperature value of the issued message was “28”, which is less than 30.
This means that the message was not sent to the SNS topic because it did not meet the requirements of the AWS IoT rule.

Summary

AWS IoT rules can be used to notify SNS of messages.
Appropriate use of the WHERE clause can be used to limit the target messages.

TOC