AWS IoT

ESP32 IDF 기반 AWS IoT 디바이스 구현

임베디드 친구 2025. 4. 15. 16:44
728x90
반응형

ESP32 IDF 기반 AWS IoT 디바이스 구현

1. 개요

ESP32는 저전력 Wi-Fi 및 Bluetooth 기능을 제공하는 강력한 MCU로, 다양한 IoT 애플리케이션에 적합합니다. AWS IoT Core와 연동하여 온도 센싱 데이터를 송수신하는 IoT 디바이스를 구현하는 것이 이번 포스팅의 목표입니다. 이를 위해 ESP-IDFAWS IoT Device SDK for Embedded C를 활용합니다.

2. 프로젝트 개요

본 프로젝트에서는 ESP32 디바이스가 온도를 측정하고, 이를 AWS IoT Core로 전송하는 시스템을 구현합니다. AWS IoT Core는 MQTT 프로토콜을 통해 데이터를 수집하며, IoT Device Shadow를 활용하여 원격에서 센싱 주기 및 디바이스 상태를 관리합니다.

3. 개발 환경 설정

3.1 ESP-IDF 설치

ESP32를 프로그래밍하기 위해 Espressif에서 제공하는 ESP-IDF (Espressif IoT Development Framework)를 설치해야 합니다.

# ESP-IDF 리포지토리 클론
git clone --recursive https://github.com/espressif/esp-idf.git
cd esp-idf

# 필요한 패키지 설치
./install.sh

# 환경 변수 설정
. ./export.sh

3.2 AWS IoT Device SDK for Embedded C 다운로드

AWS IoT와 통신하기 위해 AWS IoT Device SDK for Embedded C를 사용합니다. SDK를 다운로드하고 ESP-IDF 프로젝트에 추가합니다.

# AWS IoT Device SDK 다운로드
git clone https://github.com/aws/aws-iot-device-sdk-embedded-C.git

4. AWS IoT 설정

4.1 AWS IoT Thing 등록 및 인증서 발급

AWS IoT 콘솔에서 Thing을 등록하고 인증서를 생성합니다.

  1. AWS IoT Core에 접속
  2. Manage → Things에서 새로운 Thing 생성
  3. X.509 인증서 생성 후 다운로드
  4. Thing과 인증서를 연결한 후, AWS IoT Policy 생성 및 적용

4.2 MQTT 엔드포인트 확인

AWS IoT Core의 Settings에서 MQTT 엔드포인트를 확인하고, ESP32에서 사용할 수 있도록 설정합니다.

5. ESP32 코드 구현

5.1 프로젝트 디렉터리 구조

aws_iot_project/
│── main/
│   ├── main.c
│   ├── aws_iot.c
│   ├── aws_iot.h
│── components/
│── sdkconfig
│── CMakeLists.txt
│── prj.conf

5.2 main.c (메인 프로그램)

ESP32가 Wi-Fi에 연결된 후, AWS IoT Core와 MQTT 프로토콜을 사용하여 데이터를 송수신하는 로직을 구현합니다.

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "wifi.h"
#include "aws_iot.h"

void app_main() {
    nvs_flash_init();
    wifi_init();
    aws_iot_init();
    aws_iot_publish_temperature();
    while (1) {
        vTaskDelay(pdMS_TO_TICKS(5000));
    }
}

5.3 aws_iot.c (AWS IoT 연결 및 MQTT 통신)

#include "aws_iot.h"
#include "aws_iot_mqtt_client.h"
#include "aws_iot_mqtt_client_interface.h"

#define AWS_IOT_ENDPOINT "YOUR_AWS_IOT_ENDPOINT"
#define CLIENT_ID "esp32_device"
#define TOPIC "iot/temperature"

void aws_iot_publish_temperature() {
    IoT_Client_Init_Params mqttInitParams = iotClientInitParamsDefault;
    IoT_Client_Connect_Params connectParams = iotClientConnectParamsDefault;
    mqttInitParams.enableAutoReconnect = false;
    mqttInitParams.pHostURL = AWS_IOT_ENDPOINT;
    mqttInitParams.port = 8883;
    aws_iot_mqtt_init(&mqttClient, &mqttInitParams);

    connectParams.keepAliveIntervalInSec = 10;
    connectParams.clientIDLen = (uint16_t) strlen(CLIENT_ID);
    connectParams.isCleanSession = true;

    if (aws_iot_mqtt_connect(&mqttClient, &connectParams) == SUCCESS) {
        char message[50];
        sprintf(message, "{\"temperature\": 25.5}");
        aws_iot_mqtt_publish(&mqttClient, TOPIC, strlen(TOPIC), message, strlen(message), 0, false);
    }
}

6. AWS IoT 서버 코드 (Python)

AWS IoT Core에서 MQTT 메시지를 수신하고, 특정 온도 범위를 벗어나는 데이터를 감지하는 간단한 Python 스크립트를 작성합니다.

import paho.mqtt.client as mqtt
import json

AWS_IOT_ENDPOINT = "YOUR_AWS_IOT_ENDPOINT"
TOPIC = "iot/temperature"

# MQTT 메시지 수신 콜백
def on_message(client, userdata, msg):
    payload = json.loads(msg.payload)
    temperature = payload.get("temperature")
    if temperature and (temperature < 15 or temperature > 30):
        print(f"경고: 온도 범위 초과 - {temperature}도")

# MQTT 설정
client = mqtt.Client()
client.on_message = on_message
client.connect(AWS_IOT_ENDPOINT, 8883)
client.subscribe(TOPIC)
client.loop_forever()

7. 테스트 및 배포

  1. ESP32 빌드 및 플래시
    idf.py build
    idf.py flash
  2. AWS IoT Core에서 MQTT 메시지 확인
    • AWS IoT 콘솔의 MQTT 테스트 클라이언트에서 메시지를 구독(subscribe)하여 디바이스에서 전송한 온도 데이터를 확인합니다.
  3. Python 스크립트를 실행하여 AWS IoT Core에서 데이터를 수신하고 처리하는지 확인합니다.

8. 결론

본 포스팅에서는 ESP32 IDF 기반의 AWS IoT 디바이스를 구현하는 과정을 다루었습니다. ESP32가 센서를 통해 온도를 측정하고 AWS IoT Core로 전송하는 방법을 설명하였으며, 이를 처리하는 AWS IoT 서버 코드(Python)도 함께 구현하였습니다. AWS IoT를 활용하여 보다 확장성 있는 IoT 애플리케이션을 개발할 수 있습니다.

반응형