AWS IoT

AWS IoT Core를 이용한 기본 설정

임베디드 친구 2025. 3. 25. 08:26
728x90
반응형

AWS IoT Core를 이용한 기본 설정

1. 개요

AWS IoT Core는 AWS에서 제공하는 클라우드 기반 IoT 서비스로, 다양한 IoT 디바이스와 안전하게 연결하고 데이터를 송수신할 수 있도록 지원합니다. 본 포스팅에서는 AWS IoT Core의 기본 설정 방법을 소개하고, ESP32를 이용한 온도 센싱 디바이스 예제를 구현하여 AWS IoT 서버와의 연동을 설명하겠습니다.

2. AWS IoT Core 설정

2.1 AWS IoT 콘솔 접속 및 사물(Thing) 등록

  1. AWS 콘솔(https://aws.amazon.com/console/)에 로그인합니다.
  2. AWS IoT Core 서비스로 이동합니다.
  3. 좌측 메뉴에서 Manage > Things를 선택합니다.
  4. Create Things 버튼을 클릭하고, 원하는 사물(Thing) 이름을 입력합니다.
  5. 디바이스 유형은 "Single Thing"을 선택하고, 계속 진행합니다.

2.2 인증서 생성 및 정책 설정

  1. 새로운 인증서 자동 생성(Create certificate) 옵션을 선택합니다.
  2. 생성된 인증서를 다운로드하고, public key, private key, root CA 파일을 저장합니다.
  3. 인증서를 활성화한 후, 정책을 생성하여 인증서에 연결합니다.
  4. Policies 메뉴에서 새로운 정책을 생성하고, 아래와 같이 정책 문서를 작성합니다.
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "iot:*",
      "Resource": "*"
    }
  ]
}
  1. 생성한 정책을 인증서에 연결합니다.

2.3 MQTT 테스트 및 엔드포인트 확인

  1. Settings 메뉴에서 Device data endpoint를 확인하고 복사합니다.
  2. MQTT test client를 이용하여 메시지를 퍼블리시/구독할 수 있는지 확인합니다.

3. ESP32 IoT 디바이스 설정

ESP32 디바이스에서 AWS IoT Core와 통신하기 위해 ESP-IDFAWS IoT Device SDK for Embedded C를 사용합니다.

3.1 ESP-IDF 개발 환경 설정

ESP-IDF를 설치하고 프로젝트를 생성합니다.

# ESP-IDF 설치
mkdir -p ~/esp
cd ~/esp
git clone --recursive https://github.com/espressif/esp-idf.git
cd esp-idf
./install.sh
. ./export.sh

새 프로젝트를 생성합니다.

idf.py create-project aws_iot_example
cd aws_iot_example

3.2 AWS IoT 디바이스 SDK 설치 및 구성

ESP-IDF 프로젝트에서 AWS IoT Device SDK를 추가합니다.

git clone https://github.com/aws/aws-iot-device-sdk-embedded-C.git components/aws-iot-sdk

디바이스 코드(main/main.c)를 작성합니다.

#include <stdio.h>
#include "aws_iot_mqtt_client_interface.h"

#define AWS_IOT_MQTT_HOST    "<AWS_ENDPOINT>"
#define AWS_IOT_MQTT_PORT    8883
#define CLIENT_ID            "esp32_device"
#define TOPIC                "esp32/temperature"

void app_main() {
    AWS_IoT_Client mqttClient;
    IoT_Client_Init_Params mqttInitParams = iotClientInitParamsDefault;
    mqttInitParams.enableAutoReconnect = false;
    mqttInitParams.pHostURL = AWS_IOT_MQTT_HOST;
    mqttInitParams.port = AWS_IOT_MQTT_PORT;

    IoT_Error_t rc = aws_iot_mqtt_init(&mqttClient, &mqttInitParams);
    if (rc != SUCCESS) {
        printf("MQTT Initialization failed\n");
        return;
    }

    IoT_Client_Connect_Params connectParams = iotClientConnectParamsDefault;
    connectParams.keepAliveIntervalInSec = 60;
    connectParams.isCleanSession = true;
    connectParams.MQTTVersion = MQTT_3_1_1;
    connectParams.clientIDLen = (uint16_t) strlen(CLIENT_ID);
    connectParams.pClientID = CLIENT_ID;

    rc = aws_iot_mqtt_connect(&mqttClient, &connectParams);
    if (rc != SUCCESS) {
        printf("MQTT Connection failed\n");
        return;
    }

    char payload[100];
    sprintf(payload, "{\"temperature\": %d}", 25);
    aws_iot_mqtt_publish(&mqttClient, TOPIC, strlen(TOPIC), payload, strlen(payload), QOS0);
}

ESP32에 코드를 빌드하고 플래시합니다.

idf.py build
idf.py flash

4. AWS IoT 서버 코드 (Python)

AWS IoT Core에서 수신한 데이터를 처리하는 서버를 Python으로 작성합니다.

import paho.mqtt.client as mqtt

BROKER_ENDPOINT = "<AWS_ENDPOINT>"
TOPIC = "esp32/temperature"
CLIENT_ID = "aws_server"

# 메시지 수신 콜백 함수
def on_message(client, userdata, message):
    print(f"Received message: {message.payload.decode()} from topic: {message.topic}")

client = mqtt.Client(CLIENT_ID)
client.tls_set(ca_certs="root-CA.crt", certfile="device.pem.crt", keyfile="private.pem.key")
client.connect(BROKER_ENDPOINT, 8883)
client.subscribe(TOPIC)
client.on_message = on_message

print("Listening for messages...")
client.loop_forever()

5. 결론

본 포스팅에서는 AWS IoT Core를 설정하고 ESP32를 이용하여 온도 데이터를 AWS 클라우드로 전송하는 방법을 설명하였습니다. 이를 통해 IoT 디바이스와 클라우드의 기본적인 연동을 수행할 수 있으며, 향후 확장하여 다양한 센서 데이터를 처리하는 IoT 시스템을 구축할 수 있습니다.

728x90
반응형