Send retained messages from a thing to AWS IoT Core

Introduction

When sending a normal MQTT message, if there are no subscribers to a topic when the message is received, the broker simply discards the message. However, some messages are important and should be shared not only with the current live subscribers (if any) but also with the future subscribers. This can be achieved by setting the RETAIN flag in the sent message. You can read more about retained messages here.

Sending Retained Messages from a Thing

If you wish to send retained messages from a thing, you need to do the following:

Policy Changes

Edit the policy attached to the certificate of the thing, and provide the iot:retainPublish permissions for the relevant topics. For example, in the How to connect ESP32 to AWS IoT Core tutorial, we configured the thing to publish to the esp32/pub topic. Now, in order to permit it to publish RETAIN flag messages to this topic, the policy changes as follows:

{
      "Effect": "Allow",
      "Action": "iot:Publish",

      "Resource": "arn:aws:iot:us-east-2:your-account:topic/esp32/pub"
}

changes to:

{
      "Effect": "Allow",
      "Action": [
        "iot:Publish",
        "iot:RetainPublish"
      ],
      "Resource": "arn:aws:iot:us-east-2:your-account:topic/esp32/pub"
}

You can see more examples on policy changes for retained messages here.

Firmware Changes

Check the source code of the MQTT library you are using and determine the equivalent publish function with the retained boolean argument. For example, the PubSubClient library has these variations for the publish function. Similarly, the arduino-mqtt library used in the How to connect ESP32 to AWS IoT Core tutorial has these variations of the publish function.

Replace the existing .publish() function in your firmware with an equivalent function allowing you to set the retained flag. If you are not using any library for mqtt, but rather constructing the packet yourself, see the packet structure here for reference.

Check Retained Messages on AWS IoT Core

On AWS IoT Core console, click on the ‘Manage’ tab from the left menu, and click on ‘Retained messages’. For every topic which has a retained message published to it, you will be able to see the latest retained message. This is important to understand. Only one message is retained per topic. As soon as a new message is retained, it replaces the old one.

Viewing retained messages

I hope you liked this article. For more tutorials on AWS, check out https://iotespresso.com/category/aws/. Also, if you are planning to become a certified AWS Solutions Architect, I’d recommend that you check out this course on Udemy. I took this course and found the lectures to be lucid, to-the-point, and fun. I hope they will help you as well.

1 comment

Leave a comment

Your email address will not be published. Required fields are marked *