1. Apa Itu AWS IoT Core?
AWS IoT Core adalah managed cloud platform yang memungkinkan kamu menghubungkan miliaran perangkat IoT ke AWS Cloud. Platform ini menyediakan MQTT broker yang scalable, device management, data processing, dan integrasi penuh dengan seluruh ekosistem AWS (Lambda, DynamoDB, S3, SNS, dll).
Keunggulan utama AWS IoT Core adalah skalabilitas enterprise-grade dan keamanan berlapis. Setiap device terhubung menggunakan X.509 certificate atau custom authorizer, dan semua komunikasi terenkripsi TLS. Rules Engine memungkinkan routing data ke berbagai AWS service tanpa kode.
AWS IoT Core menggunakan MQTT 3.1.1 dengan extensions. Mendukung MQTT Quality of Service (QoS) 0 dan 1. Untuk device yang sering offline, gunakan persistent sessions dengan QoS 1.
Fitur Utama
| Fitur | Deskripsi |
|---|---|
| Message Broker | MQTT broker managed yang mendukung jutaan koneksi simultan |
| Device Shadow | Virtual representation dari device state (desired vs reported) |
| Rules Engine | Route message ke AWS services berdasarkan filter SQL |
| Fleet Provisioning | Provisi massal device dengan certificate dan policy otomatis |
| Device Defender | Security audit dan anomaly detection untuk device fleet |
| Jobs | Remote device management: OTA update, restart, factory reset |
| Greengrass | Edge runtime untuk local compute, ML inference, dan messaging |
2. Setup AWS IoT Core
Membuat IoT Thing
# Menggunakan AWS CLI
# 1. Buat Thing Type
aws iot create-thing-type --thing-type-name "SensorDevice"
# 2. Buat Thing
aws iot create-thing \
--thing-name "sensor-01" \
--thing-type-name "SensorDevice" \
--attribute-payload '{"attributes":{"location":"warehouse-A","type":"temperature"}}'
# 3. Buat Certificate
aws iot create-keys-and-certificate \
--set-as-active \
--certificate-pem-outfile sensor-01.cert.pem \
--public-key-outfile sensor-01.public.key \
--private-key-outfile sensor-01.private.key
# 4. Buat Policy
aws iot create-policy \
--policy-name "SensorPolicy" \
--policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["iot:Connect", "iot:Publish", "iot:Subscribe", "iot:Receive"],
"Resource": ["arn:aws:iot:REGION:ACCOUNT:client/sensor-*",
"arn:aws:iot:REGION:ACCOUNT:topic/sensors/*",
"arn:aws:iot:REGION:ACCOUNT:topicfilter/sensors/*"]
}]
}'
# 5. Attach Policy ke Certificate
aws iot attach-policy \
--policy-name "SensorPolicy" \
--target "CERTIFICATE_ARN"
# 6. Attach Certificate ke Thing
aws iot attach-thing-principal \
--thing-name "sensor-01" \
--principal "CERTIFICATE_ARN"
# 7. Download Root CA
curl -o root-CA.crt https://www.amazontrust.com/repository/AmazonRootCA1.pem
Struktur Sertifikat
# File yang dibutuhkan untuk koneksi TLS:
# - root-CA.crt : Amazon Root CA certificate
# - sensor-01.cert.pem : Certificate device (dari step 3)
# - sensor-01.private.key : Private key device (dari step 3)
# - sensor-01.public.key : Public key device (untuk referensi)
# Endpoint IoT Core:
# - Data: xxxxxxxxxx-ats.iot.ap-southeast-1.amazonaws.com
# - Credential: credentials.iot.ap-southeast-1.amazonaws.com
# Untuk mendapatkan endpoint:
aws iot describe-endpoint --endpoint-type-iot:Data-ATS
3. MQTT Broker & Topics
AWS IoT Core MQTT broker mendukung topic-based messaging dengan wildcard subscription. Broker juga memiliki reserved topics untuk fitur khusus seperti device shadow dan jobs.
MQTT Topic Structure
# Topic umum (custom):
sensors/temperature/warehouse-a
devices/sensor-01/telemetry
factory/line-1/machine-3/status
# Reserved Topics (AWS IoT Core specific):
$aws/things/{thingName}/shadow/update # Device shadow update
$aws/things/{thingName}/shadow/get # Get device shadow
$aws/things/{thingName}/jobs/notify # Job notification
$aws/things/{thingName}/jobs/{jobId}/update # Job status update
$aws/things/{thingName}/defender/metrics # Device Defender metrics
$aws/events/presence/connected/{clientId} # Device connect event
$aws/events/presence/disconnected/{clientId} # Device disconnect event
# Wildcard:
sensors/# # Semua subtopic dari sensors
+/temperature/# # Semua device temperature data
MQTT Testing
# Subscribe menggunakan mosquitto CLI
mosquitto_sub \
--cafile root-CA.crt \
--cert sensor-01.cert.pem \
--key sensor-01.private.key \
-h xxxxxxxxxx-ats.iot.ap-southeast-1.amazonaws.com \
-p 8883 \
-t "sensors/+/data" \
--tls-version tlsv1.2
# Publish test message
mosquitto_pub \
--cafile root-CA.crt \
--cert sensor-01.cert.pem \
--key sensor-01.private.key \
-h xxxxxxxxxx-ats.iot.ap-southeast-1.amazonaws.com \
-p 8883 \
-t "sensors/temperature/data" \
-m '{"temp": 25.6, "humidity": 65}' \
--tls-version tlsv1.2
# AWS CLI — Publish ke MQTT topic
aws iot-data publish \
--topic "sensors/temperature/data" \
--payload '{"temp": 25.6, "humidity": 65}'
4. Device Shadows (State Management)
Device Shadow adalah JSON document yang menyimpan state terkini dari device. Shadow memungkinkan aplikasi membaca dan mengubah state device meskipun device sedang offline. Shadow memiliki dua bagian: desired (state yang diinginkan) dan reported (state aktual dari device).
Shadow Document Structure
{
"state": {
"desired": {
"led": "on",
"report_interval": 30,
"temperature_threshold": 40,
"clientToken": "client-001"
},
"reported": {
"led": "off",
"report_interval": 60,
"temperature_threshold": 35,
"firmware_version": "2.1.0",
"battery": 87
}
},
"metadata": {
"desired": {
"led": { "timestamp": 1719600000 },
"report_interval": { "timestamp": 1719600000 }
},
"reported": {
"led": { "timestamp": 1719600000 },
"report_interval": { "timestamp": 1719600060 }
}
},
"version": 123,
"timestamp": 1719600120
}
Update Shadow dari Aplikasi
# Update desired state (dari backend/app)
aws iot-data update-thing-shadow \
--thing-name "sensor-01" \
--payload '{
"state": {
"desired": {
"led": "on",
"report_interval": 30
}
}
}' shadow-output.json
# Get current shadow
aws iot-data get-thing-shadow \
--thing-name "sensor-01" \
shadow-output.json
# Delete shadow
aws iot-data delete-thing-shadow \
--thing-name "sensor-01"
Shadow di Device (ESP32)
// ESP32: Update reported state
void updateShadow(const char* reportedState) {
String topic = "$aws/things/sensor-01/shadow/update";
String payload = "{"state":{"reported":";
payload += reportedState;
payload += "}}";
mqttClient.publish(topic.c_str(), payload.c_str());
}
// ESP32: Listen for desired state changes
void onShadowDelta(const char* topic, byte* payload, unsigned int length) {
// Parse delta — perbedaan antara desired dan reported
StaticJsonDocument<512> doc;
deserializeJson(doc, payload);
JsonObject state = doc["state"];
if (state.containsKey("led")) {
String ledState = state["led"];
digitalWrite(LED_PIN, ledState == "on" ? HIGH : LOW);
// Update reported setelah perubahan diterapkan
updateShadow("{"led":"on"}");
}
}
// Subscribe ke shadow delta
mqttClient.subscribe("$aws/things/sensor-01/shadow/update/delta");
5. Rules Engine & Data Routing
Rules Engine memproses incoming MQTT messages berdasarkan SQL-like query dan meng-arahkan hasilnya ke berbagai AWS service. Ini adalah salah satu fitur terkuat AWS IoT Core.
Membuat Rule
# SQL Rule: Filter sensor data suhu tinggi
# SELECT statement:
SELECT temperature, humidity, deviceName, timestamp()
FROM 'sensors/+/data'
WHERE temperature > 35
# Rule Actions (pilih salah satu atau kombinasi):
# 1. Lambda — trigger fungsi untuk processing
# 2. DynamoDB — simpan ke database
# 3. S3 — archive raw data
# 4. SNS — kirim notifikasi
# 5. SQS — queue untuk async processing
# 6. Kinesis Firehose — streaming ke data lake
# 7. Elasticsearch — indexing untuk search
# 8. IoT Analytics — analisis data IoT
Contoh Rules untuk IoT
# Rule 1: Simpan semua telemetry ke DynamoDB
SELECT *, timestamp() as ts FROM 'sensors/+/data'
→ Action: DynamoDB (table: IoTTelemetry, hash: deviceName, range: ts)
# Rule 2: Alert suhu tinggi ke SNS
SELECT temperature, deviceName, timestamp() as ts
FROM 'sensors/+/data'
WHERE temperature > 40
→ Action: SNS (topic: high-temp-alerts)
# Rule 3: Archive ke S3
SELECT * FROM 'sensors/#'
→ Action: S3 (bucket: iot-data-archive, key: ${topic()}/${timestamp()})
# Rule 4: Lambda processing
SELECT * FROM 'devices/+/commands'
→ Action: Lambda (function: processDeviceCommand)
# Rule 5: Geo-location processing
SELECT deviceName, location.latitude, location.longitude, timestamp()
FROM 'trackers/+/location'
WHERE distance(location.latitude, location.longitude, -6.2088, 106.8456) > 1000
→ Action: SNS (geofence-violation)
6. Fleet Provisioning
Fleet Provisioning memungkinkan provisi massal perangkat IoT secara otomatis. Daripada membuat certificate satu per satu, kamu bisa menggunakan provisioning template yang otomatis menghasilkan certificate, mendaftarkan thing, dan attach policy.
# 1. Buat Provisioning Template
aws iot create-provisioning-template \
--template-name "SensorProvisioning" \
--description "Template for sensor devices" \
--provisioning-role-arn "arn:aws:iam::ACCOUNT:role/IoTProvisioningRole" \
--template-body '{
"Parameters": {
"SerialNumber": {"Type": "String"},
"Location": {"Type": "String"}
},
"Resources": {
"thing": {
"Type": "AWS::IoT::Thing",
"Properties": {
"ThingName": {"Ref": "SerialNumber"},
"ThingTypeName": "SensorDevice",
"AttributePayload": {
"location": {"Ref": "Location"}
}
}
},
"certificate": {
"Type": "AWS::IoT::Certificate",
"Properties": {
"CertificateId": {"Ref": "AWS::IoT::Certificate::Id"}
}
},
"policy": {
"Type": "AWS::IoT::Policy",
"Properties": {
"PolicyName": "SensorPolicy"
}
}
}
}'
# 2. Device melakukan provisioning:
# - Generate CSR (Certificate Signing Request)
# - Hubungi provisioning endpoint dengan template parameters
# - AWS mengembalikan signed certificate
# - Device menggunakan certificate untuk koneksi normal
7. Security & Authentication
AWS IoT Core menyediakan beberapa metode autentikasi: X.509 certificates (paling umum), Custom Authorizer (Lambda-based), dan IAM credentials.
Security Best Practices
| Praktik | Deskripsi |
|---|---|
| Certificate per Device | Setiap device harus memiliki certificate unik |
| Least-Privilege Policy | Batasi aksi dan resource yang diperbolehkan |
| Certificate Rotation | Rotate certificate sebelum expired |
| Custom Authorizer | Gunakan Lambda untuk autentikasi kustom |
| TLS 1.2+ | Wajib menggunakan TLS untuk semua koneksi |
| Device Defender | Monitor anomali koneksi dan credential usage |
8. ESP32 + AWS IoT Core
// ESP32 + AWS IoT Core via MQTT
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
const char* WIFI_SSID = "your-wifi";
const char* WIFI_PASS = "your-password";
const char* AWS_IOT_ENDPOINT = "xxxxx-ats.iot.ap-southeast-1.amazonaws.com";
const int AWS_IOT_PORT = 8883;
const char* THING_NAME = "sensor-01";
// Certificate files (di-embed atau dari SPIFFS/LittleFS)
const char ROOT_CA[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
... Amazon Root CA 1 ...
-----END CERTIFICATE-----
)EOF";
const char DEVICE_CERT[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
... Device Certificate ...
-----END CERTIFICATE-----
)EOF";
const char DEVICE_KEY[] PROGMEM = R"EOF(
-----BEGIN RSA PRIVATE KEY-----
... Device Private Key ...
-----END RSA PRIVATE KEY-----
)EOF";
WiFiClientSecure net;
PubSubClient client(net);
void connectWiFi() {
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) delay(500);
}
void connectAWS() {
net.setCACert(ROOT_CA);
net.setCertificate(DEVICE_CERT);
net.setPrivateKey(DEVICE_KEY);
client.setServer(AWS_IOT_ENDPOINT, AWS_IOT_PORT);
while (!client.connected()) {
if (client.connect(THING_NAME)) {
client.subscribe("$aws/things/" + String(THING_NAME) + "/shadow/update/delta");
client.subscribe("$aws/things/" + String(THING_NAME) + "/jobs/notify");
} else {
delay(5000);
}
}
}
void publishTelemetry(float temp, float humidity) {
StaticJsonDocument<200> doc;
doc["temperature"] = temp;
doc["humidity"] = humidity;
doc["device"] = THING_NAME;
char buffer[200];
serializeJson(doc, buffer);
String topic = "sensors/" + String(THING_NAME) + "/data";
client.publish(topic.c_str(), buffer);
}
void setup() {
Serial.begin(115200);
connectWiFi();
connectAWS();
}
void loop() {
if (!client.connected()) connectAWS();
client.loop();
static unsigned long lastSend = 0;
if (millis() - lastSend > 10000) {
float temp = readTemperature();
float hum = readHumidity();
publishTelemetry(temp, hum);
lastSend = millis();
}
}
9. Quiz: Uji Pemahamanmu!
Setelah membaca tutorial di atas, jawablah 5 pertanyaan berikut untuk menguji pemahamanmu tentang AWS IoT Core: