AWS IoT – Intro (part 1)

This blog series will give you an introduction to AWS Internet of Things (IoT) device management. We’ll be using a tiny IoT device that sends sensor data to AWS, and also confirm we can send messages back to the device. This post is a slight change in direction — the world we live in is evolving, and a lot of the DevOps tasks I used to do can now be easily handled by AI. Before my cloud journey, I spent a bit of time experimenting with Arduino and ESP32 devices. I’ve decided to go back to experimenting with these devices and get them communicating with AWS in both directions.

For my IoT hardware I’m going to use an Espressif ESP32-C6 device. This System on Chip (SoC) integrates microcontrollers, peripherals, GPIOs, and wireless connectivity (Wi-Fi, Bluetooth LE, and Zigbee) directly onto the chip, which makes it a good candidate for entry-level IoT experiments. The device is about the size of a thumbnail and can be purchased for less than USD $6 from Seeed Studio.

The overview of the solution components are shown below:



The main components are:
IOT Hardware: ESP32-C6 with firmware and configuration files

Local device: a laptop with physical connectivity to the ESP32, used to initially bootstrap the device with firmware, Wi-Fi configuration, and an AWS IoT certificate (for secure communication with AWS). The laptop will need Python, some OS build tools, and the Espressif toolchain to build the files. A toolchain is a set of tools that turns source code into a runnable binary/firmware for a specific target. The runnable binaries are loaded into the device’s flash memory (4MB on the ESP32-C6).

In our AWS account we will:

  • confirm our regional IoT endpoint
  • create an IoT Thing (which represents our physical device)
  • create an X.509 certificate for secure communications
  • attach an access policy to our Thing

There are some tasks to complete on the local device too — namely building the firmware and configuration files the hardware needs. Normally we’d do this using a Docker container in AWS, but since we initially need physical connectivity to bootstrap the device, local connectivity is required instead. The steps below are based on macOS, but an equivalent process can be followed on other operating systems.

When working with the ESP32 there are a few choices for firmware. I started off using MicroPython (https://micropython.org/download/ESP32_GENERIC_C6/ ). I was able to use the esptool and mpremote tools to upload firmware and a basic program that would blink the built-in LED on the device. However, I found MicroPython had limited Over-the-Air (OTA) agent support, so I would have had to write my own processes for communicating with AWS IoT.

Luckily, Espressif provides the ESP-IDF (ESP IoT Development Framework), which gives you the low-level building blocks: a Wi-Fi driver, esp-tls (the TLS transport), mbedTLS, FreeRTOS, and the component build system. We’ll also need esp-aws-iot, which is Espressif’s packaging of the AWS IoT Device SDK for Embedded C — including protocol libraries such as coreMQTT, coreHTTP, coreJSON, corePKCS11, Device Shadow, Jobs, and Fleet Provisioning — built to run on top of ESP-IDF.

Step 1 – Prerequisites

Before we install the toolchain, we’ll need to install some prerequisites as detailed in the ESP-IDF Get Started guide for your operating system. The following steps are for macOS.

brew install cmake ninja dfu-util python3
  • `cmake` — build system generator ESP-IDF uses to configure the project build
  • `ninja` — fast build tool that actually compiles/links, invoked by cmake
  • `dfu-util` — USB DFU (Device Firmware Upgrade) flashing utility, used by some ESP boards for flashing over USB
  • `python3` — runs ESP-IDF’s `idf.py` tooling and its Python-based build scripts (ships with macOS already)

Device mount point discovery

We will need to know what mount point the device is registered to when you plug it into the USB port. Mine was on /dev/cu.usbmodem1101

AWS account regional IoT endpoint discovery

Use the following AWS CLI command to find your accounts regional endpoint (example below is for Sydney region, no IoT endpoint available in NZ yet)

aws iot describe-endpoint --endpoint-type iot:Data-ATS --region ap-southeast-2
{
"endpointAddress": "ZZZZZZZZZZ-ats.iot.ap-southeast-2.amazonaws.com"
}

Step 2: ESP-IDF install

We’ll be installing esp-aws-iot on top of ESP-IDF. At the time of writing, esp-aws-iot’s LTS branch supports ESP-IDF v6.0. Create a folder for your toolchain.

cd ~
mkdir -p <your folder> && cd <your folder>
git clone -b v6.0.3 --recursive https://github.com/espressif/esp-idf.git esp-idf

By default, installer files are cloned into a subfolder under your folder ie ~/<your folder>/esp-idf. The esp-idf installer will install components under the root of your home folder and will make tidy up harder. To keep everything self-contailned in our project folder instead, set the IDF_TOOLS_PATH environment variable before running the installer. Note that the installer will also create its own Python virtual environment, named idf<major.minor>_py_env (e.g. idf6.0_py3.15_env), as part of the install script.

export IDF_TOOLS_PATH="$HOME/<your folder>/esp-idf-tools"
cd esp-idf
./install.sh esp32c6
. ./esp-idf/export.sh

Create an ESP-IDF project

cd..
idf.py create-project esp32-c6-demo-project

Add the AWS SDK for embedded c devices

cd ~/<your folder>
git clone -b release/202406.05-LTS --recursive https://github.com/espressif/esp-aws-iot.git esp-aws-iot

Update esp32-c6-demo-project/CMakeLists.txt to include the MQTT and example libraries. At the same time we create the links to the AWS certificate we will provision later.

set(EXTRA_COMPONENT_DIRS
"${CMAKE_CURRENT_LIST_DIR}/../esp-aws-iot/libraries/backoffAlgorithm"
"${CMAKE_CURRENT_LIST_DIR}/../esp-aws-iot/libraries/coreMQTT"
"${CMAKE_CURRENT_LIST_DIR}/../esp-aws-iot/libraries/common/posix_compat"
"$ENV{IDF_PATH}/examples/common_components/protocol_examples_common"
)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(esp32-c6-demo-project)
target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/root_cert_auth.crt" TEXT)
target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/client.crt" TEXT)
target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/client.key" TEXT)

We need to create a new file to define schema for build in ~/<your folder>/esp32-c6-demo-project/main/Kconfig.projbuild

cat > ~/<your folder>/esp32-c6-demo-project/main/Kconfig.projbuild << 'EOF'
menu "AWS IoT Configuration"
config AWS_IOT_ENDPOINT
string "AWS IoT endpoint (from: aws iot describe-endpoint)"
default ""
help
The account-specific AWS IoT Core endpoint this device connects to.
config AWS_IOT_MQTT_PORT
int "MQTT port"
default 8883
help
8883 for standard TLS MQTT; use 443 only if ALPN is configured.
config AWS_IOT_MQTT_CLIENT_IDENTIFIER
string "MQTT client identifier (must match the Thing name)"
default "esp32_demo_thing"
config AWS_IOT_MQTT_NETWORK_BUFFER_SIZE
int "Size of the network buffer for MQTT packets"
range 1024 2048
default 1024
choice AWS_IOT_PKI_ACCESS_METHOD
prompt "Choose PKI credentials access method"
default AWS_IOT_USE_PLAIN_FLASH_STORAGE
help
Default is to embed the cert/key from main/certs/ directly in the binary.
config AWS_IOT_USE_PLAIN_FLASH_STORAGE
bool "Use flash storage (default)"
endchoice
endmenu
EOF

Step 3 – Update build parameters with your environment and setup

Create file ~/<your folder>/esp32-c6-demo-project/sdkconfig.defaults with your enviroment values. Note, The IoT endpoint was gathered in Step 1.

cat > ~/<your folder>/esp32-c6-demo-project/sdkconfig.defaults << 'EOF'
CONFIG_EXAMPLE_WIFI_SSID="your-wifi-ssid"
CONFIG_EXAMPLE_WIFI_PASSWORD="your-wifi-password"
CONFIG_AWS_IOT_ENDPOINT="xxxxxxxxxxxxxx-ats.iot.ap-southeast-2.amazonaws.com"
CONFIG_AWS_IOT_MQTT_CLIENT_IDENTIFIER="esp32_demo_thing"
CONFIG_PARTITION_TABLE_TWO_OTA_LARGE=y
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
EOF

Step 4 – AWS setup

Create AWS IoT thing

aws iot create-thing --thing-name esp32_demo_thing

Generate certificates and activate

cd ~/<your folder>
mkdir -p esp32-c6-demo-project/main/certs
aws iot create-keys-and-certificate \
--set-as-active \
--certificate-pem-outfile esp32-c6-demo-project/main/certs/client.crt \
--public-key-outfile /tmp/esp32-c6-demo-project_public.key \
--private-key-outfile esp32-c6-demo-project/main/certs/client.key \
--query certificateArn --output text > /tmp/cert_arn.txt
rm /tmp/esp32-c6-demo-project_public.key
curl -o esp32-c6-demo-project/main/certs/root_cert_auth.crt https://www.amazontrust.com/repository/AmazonRootCA1.pem

Create a policy that is scoped to our thing’s ID, update with region and account ID

cat > /tmp/esp32-c6-demo-project_policy.json << 'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:Connect",
"Resource": "arn:aws:iot:<REGION>:<ACCOUNT_ID>:client/esp32_demo_thing"
},
{
"Effect": "Allow",
"Action": ["iot:Publish", "iot:Receive"],
"Resource": "arn:aws:iot:<REGION>:<ACCOUNT_ID>:topic/esp32_demo_thing/*"
},
{
"Effect": "Allow",
"Action": "iot:Subscribe",
"Resource": "arn:aws:iot:<REGION>:<ACCOUNT_ID>:topicfilter/esp32_demo_thing/*"
}
]
}
EOF
aws iot create-policy --policy-name esp32_demo_thing_policy --policy-document file:///tmp/esp32-c6-demo-project_policy.json

Attach policy and thing to certificate

CERT_ARN=$(cat /tmp/cert_arn.txt)
aws iot attach-policy --policy-name esp32_demo_thing_policy --target "$CERT_ARN"
aws iot attach-thing-principal --thing-name esp32_demo_thing --principal "$CERT_ARN"

Next we need to enable the MQTT/TLS connection logic by copying over the example file from esp-aws-iot into our project:

cp ~/<your folder>/esp-aws-iot/examples/mqtt/tls_mutual_auth/main/mqtt_demo_mutual_auth.c \
~/<your folder>/esp32-c6-demo-project/main/mqtt_demo_mutual_auth.c

Update the file with two changes so that CLIENT_IDENTIFIER “/example/topic” is now CLIENT_IDENTIFIER “push/notification” around line 184 and

Change the default message from “Hello World!” to “Hello from ESP32-C6!” around line 194.

Create a new file ~/<your folder>/esp32-c6-demo-project/main/demo_config.h with:

#ifndef DEMO_CONFIG_H_
#define DEMO_CONFIG_H_
#include "logging_levels.h"
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "MQTT_DEMO"
#endif
#ifndef LIBRARY_LOG_LEVEL
#define LIBRARY_LOG_LEVEL LOG_INFO
#endif
#include "logging_stack.h"
#ifndef AWS_IOT_ENDPOINT
#define AWS_IOT_ENDPOINT CONFIG_AWS_IOT_ENDPOINT
#endif
#ifndef AWS_MQTT_PORT
#define AWS_MQTT_PORT ( CONFIG_AWS_IOT_MQTT_PORT )
#endif
#ifndef CLIENT_IDENTIFIER
#define CLIENT_IDENTIFIER CONFIG_AWS_IOT_MQTT_CLIENT_IDENTIFIER
#endif
#define NETWORK_BUFFER_SIZE ( CONFIG_AWS_IOT_MQTT_NETWORK_BUFFER_SIZE )
#define OS_NAME "FreeRTOS"
#define OS_VERSION tskKERNEL_VERSION_NUMBER
#define HARDWARE_PLATFORM_NAME "ESP32C6"
#include "core_mqtt.h"
#define MQTT_LIB "core-mqtt@" MQTT_LIBRARY_VERSION
#endif /* ifndef DEMO_CONFIG_H_ */

Update file ~/<your folder>/esp32-c6-demo-project/main/esp32-c6-demo-project.c with:

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "protocol_examples_common.h"
#include "esp_log.h"
int aws_iot_demo_main( int argc, char ** argv );
static const char *TAG = "ESP32_C6_DEMO";
void app_main( void )
{
ESP_LOGI(TAG, "[APP] Startup..");
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ESP_ERROR_CHECK(nvs_flash_init());
}
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
/* Blocks until Wi-Fi is connected and an IP address obtained. */
ESP_ERROR_CHECK(example_connect());
aws_iot_demo_main(0, NULL);
}

Update ~/<your folder>/esp32-c6-demo-project/main/CMakeLists.txt with new source files:

idf_component_register(SRCS "esp32-c6-demo-project.c" "mqtt_demo_mutual_auth.c"
INCLUDE_DIRS "."
EMBED_TXTFILES "certs/root_cert_auth.crt" "certs/client.crt" "certs/client.key")

Step 5 – Build and flash

cd ~/<your folder>/esp32-c6-demo-project
idf.py set-target esp32c6
idf.py build
idf.py -p /dev/cu.usbmodem1101 flash monitor

Hopefully your terminal will show your esp32 connecting your Wi-Fi and sending and receiving a messages (see below). The ESP32 is in a continous loop to exit the monitoring of the device type “CTRL + ]”



AWS IoT Intro part 1 wrap-up

At this stage, the ESP32-C6 device will:

  • Boot ESP-IDF and intiates networking
  • Connects to Wi-Fi
  • Establish MQTT session with AWS
  • Subscribe to esp32_demo_thing/push/notification channel
  • Publish “Hello from ESP320C6!” to topic
  • Since our ESP32 subscribes to the same topic it publishes on we got the message our original message back.

This blog is getting too long, I will continue the build in part 2. I would encourage readers to confirm everything we had done so far in the AWS console. It is possible to subscribe (and publish) to our ‘thing’ using the ‘MQTT test client’ within the AWS IoT console.

Test publishing a message

It will show up the subscribed messages:

Leave a Reply