1. Apa Itu Azure IoT Hub?
Azure IoT Hub adalah layanan cloud managed dari Microsoft Azure yang bertindak sebagai central message hub untuk komunikasi antara aplikasi IoT dan device. IoT Hub mendukung berbagai protokol (MQTT, AMQP, HTTPS) dan menyediakan fitur enterprise-grade untuk manajemen device, keamanan, dan data processing.
Fitur unik Azure IoT Hub meliputi Device Twins (JSON document sinkronisasi state), Direct Methods (RPC ke device), Message Routing (rule-based data routing ke berbagai Azure service), dan Device Provisioning Service (provisi zero-touch).
IoT Hub tersedia dalam beberapa tier: Free (8.000 msg/hari), S1 (400.000 msg/hari), S2 (6 juta msg/hari), S3 (300 juta msg/hari). Untuk development, Free tier sudah sangat cukup.
Fitur Utama
| Fitur | Deskripsi |
|---|---|
| Device-to-Cloud (D2C) | Device mengirim telemetry ke cloud |
| Cloud-to-Device (C2D) | Cloud mengirim message/command ke device |
| Device Twins | JSON document sinkronisasi state (tag, desired, reported) |
| Direct Methods | Invoke fungsi langsung di device (RPC) |
| File Upload | Upload file dari device ke Azure Blob Storage |
| Message Routing | Route message berdasarkan filter ke berbagai endpoint |
| DPS | Zero-touch device provisioning |
| IoT Edge | Runtime untuk workload di edge device |
Azure IoT Hub vs AWS IoT Core
| Aspek | Azure IoT Hub | AWS IoT Core |
|---|---|---|
| State Sync | Device Twins | Device Shadow |
| RPC | Direct Methods | MQTT + Jobs |
| File Upload | Built-in (ke Blob Storage) | Manual (via S3 presigned URL) |
| Provisioning | DPS (terpisah) | Fleet Provisioning (built-in) |
| Protokol | MQTT, AMQP, HTTPS | MQTT, HTTPS |
| Pricing Model | Per message tier | Per message + per shadow op |
2. Setup IoT Hub & Device
Membuat IoT Hub
# Menggunakan Azure CLI
# 1. Login
az login
# 2. Buat Resource Group
az group create --name iot-rg --location southeastasia
# 3. Buat IoT Hub
az iot hub create \
--name my-iothub \
--resource-group iot-rg \
--sku S1 \
--partition-count 2
# 4. Register Device
az iot hub device-identity create \
--hub-name my-iothub \
--device-id sensor-01 \
--auth-method shared_private_key
# 5. Dapatkan Connection String
az iot hub device-identity connection-string show \
--hub-name my-iothub \
--device-id sensor-01
# Output: HostName=my-iothub.azure-devices.net;DeviceId=sensor-01;SharedAccessKey=xxx
Connection String Components
# Connection String Format:
# HostName={hub}.azure-devices.net;DeviceId={deviceId};SharedAccessKey={key}
# Komponen:
# - HostName: endpoint IoT Hub
# - DeviceId: identifier unik device
# - SharedAccessKey: symmetric key untuk autentikasi
# - SharedAccessSignature: SAS token (alternatif)
# Untuk generate SAS token:
az iot hub generate-sas-token \
--hub-name my-iothub \
--device-id sensor-01 \
--duration 86400
3. Device Twins
Device Twin adalah JSON document yang menyimpan metadata, konfigurasi, dan state dari device. Sama seperti AWS Device Shadow, twin memiliki bagian desired, reported, dan tags.
Device Twin Structure
{
"deviceId": "sensor-01",
"etag": "AAAAAAAAAAI=",
"version": 5,
"tags": {
"location": "warehouse-A",
"floor": "2",
"zone": "cold-storage",
"customer": "PT. Maju Jaya"
},
"properties": {
"desired": {
"reportInterval": 30,
"temperatureThreshold": 40,
"alertEnabled": true,
"$version": 4
},
"reported": {
"reportInterval": 60,
"temperatureThreshold": 35,
"firmwareVersion": "2.1.0",
"batteryLevel": 87,
"connectivity": "WiFi",
"$version": 3
}
}
}
Mengelola Device Twins
# Update desired properties
az iot hub device-twin update \
--hub-name my-iothub \
--device-id sensor-01 \
--set properties.desired.reportInterval=30
# Query devices berdasarkan twin properties
az iot hub query \
--hub-name my-iothub \
--query-command "SELECT * FROM devices WHERE tags.location='warehouse-A'"
# Update tags (hanya dari service side)
az iot hub device-twin update \
--hub-name my-iothub \
--device-id sensor-01 \
--set tags.status="active" tags.priority="high"
4. Direct Methods
Direct Methods memungkinkan service-side code memanggil fungsi langsung di device. Ini seperti RPC — kamu mengirim request dan mendapatkan response.
# Invoke direct method ke device
az iot hub invoke-device-method \
--hub-name my-iothub \
--device-id sensor-01 \
--method-name "reboot" \
--method-payload '{"delay": 5}'
# Method: getDeviceConfig
az iot hub invoke-device-method \
--hub-name my-iothub \
--device-id sensor-01 \
--method-name "getDeviceConfig" \
--method-payload '{"section": "sensor"}'
# Response dari device:
# {"config": {"interval": 30, "threshold": 40}, "status": 200}
# Method: setFirmwareUpdate
az iot hub invoke-device-method \
--hub-name my-iothub \
--device-id sensor-01 \
--method-name "firmwareUpdate" \
--method-payload '{"url": "https://storage.blob.core.windows.net/firmware/v2.2.0.bin", "version": "2.2.0"}'
5. File Upload dari Device
IoT Hub mendukung file upload dari device langsung ke Azure Blob Storage. Device meminta SAS URI dari IoT Hub, lalu meng-upload file langsung ke storage.
# File Upload Flow:
# 1. Device meminta upload SAS URI dari IoT Hub
# 2. IoT Hub mengembalikan SAS URI + correlation ID
# 3. Device meng-upload file ke Azure Blob Storage menggunakan SAS URI
# 4. Device mengkonfirmasi upload ke IoT Hub
# 5. IoT Hub memverifikasi dan trigger notifikasi
# Konfigurasi file upload di IoT Hub:
# Azure Portal → IoT Hub → File upload
# - Storage container: pilih/konfigurasi blob storage
# - SAS TTL: masa berlaku SAS URI (default: 1 jam)
# - File notification: enable untuk notification saat upload selesai
# - Default TTL: 1 hari
6. Message Routing & Endpoints
Message Routing memungkinkan kamu mengarahkan device messages ke berbagai Azure service berdasarkan filter query. Ini mirip dengan AWS Rules Engine.
Routing Endpoints
| Endpoint | Kegunaan |
|---|---|
| Event Hub | Streaming data real-time (seperti Kafka) |
| Service Bus Queue/Topic | Message queue untuk processing |
| Blob Storage | Archive data (JSON/CSV/AVRO) |
| Cosmos DB | NoSQL database untuk telemetry |
| Custom Endpoint | Azure Function, Logic App, Event Grid |
Contoh Route Queries
# Route 1: Semua telemetry ke Event Hub
SELECT * FROM devices/messages WHERE true
→ Endpoint: Event Hub "all-telemetry"
# Route 2: Alert suhu tinggi ke Service Bus
SELECT * FROM devices/messages
WHERE $body.temperature > 40
→ Endpoint: Service Bus Queue "temperature-alerts"
# Route 3: Data dari warehouse-A ke Cosmos DB
SELECT * FROM devices/messages
WHERE tags.location = 'warehouse-A'
→ Endpoint: Cosmos DB "warehouse-data"
# Route 4: Archive semua data ke Blob Storage
SELECT * FROM devices/messages
→ Endpoint: Blob Storage "iot-archive" (format: JSON, encoding: UTF-8)
# Route 5: Device lifecycle events
SELECT * FROM devices/lifecycleEvents
WHERE type = 'deviceConnected' OR type = 'deviceDisconnected'
→ Endpoint: Event Hub "lifecycle-events"
7. Device Provisioning Service (DPS)
Device Provisioning Service (DPS) adalah layanan terpisah yang memungkinkan zero-touch provisioning. Device bisa dialokasikan ke IoT Hub yang tepat tanpa hardcoding connection string.
DPS Flow
# Zero-Touch Provisioning Flow:
# 1. Manufacture membakar device certificate dan DPS endpoint ke device
# 2. Device mengirim registration request ke DPS
# 3. DPS memverifikasi identity (certificate attestation)
# 4. DPS menentukan IoT Hub target (load balancing / geo-based)
# 5. DPS register device ke IoT Hub
# 6. DPS mengembalikan IoT Hub endpoint ke device
# 7. Device koneksi ke IoT Hub dengan assigned credentials
# DPS supports:
# - X.509 certificate attestation (paling umum)
# - TPM (Trusted Platform Module) attestation
# - Symmetric key attestation (untuk device tanpa TPM/HSM)
Setup DPS
# Buat DPS
az iot dps create \
--name my-dps \
--resource-group iot-rg \
--location southeastasia
# Hubungkan IoT Hub ke DPS
az iot dps linked-hub create \
--dps-name my-dps \
--resource-group iot-rg \
--connection-string "HostName=my-iothub.azure-devices.net;..." \
--location southeastasia
# Buat Enrollment Group
az iot dps enrollment-group create \
--dps-name my-dps \
--resource-group iot-rg \
--enrollment-id sensor-group \
--certificate-path root-ca.pem
# Dapatkan DPS endpoint
az iot dps show \
--name my-dps \
--query "properties.serviceOperationsHostName"
8. Azure IoT SDK untuk ESP32
// ESP32 + Azure IoT Hub via Azure SDK for C
// PlatformIO: lib_deps = azure/Azure SDK for C, azure/Azure IoT Hub SDK
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
const char* CONNECTION_STRING = "HostName=my-iothub.azure-devices.net;DeviceId=sensor-01;SharedAccessKey=xxx";
WiFiClientSecure wifiClient;
PubSubClient mqttClient(wifiClient);
// Generate SAS token (simplified)
String generateSASToken(String host, String key, int expirySeconds) {
// Implementation: HMAC-SHA256 dari string_to_sign dengan decoded key
// String to sign: {host}
{expiry}
// Return: SharedAccessSignature sr={host}&se={expiry}&sig={signature}
return "SharedAccessSignature sr=...&se=...&sig=...";
}
void connectAzure() {
String host = "my-iothub.azure-devices.net";
String deviceId = "sensor-01";
String sasToken = generateSASToken(host, SHARED_ACCESS_KEY, 86400);
mqttClient.setServer(host.c_str(), 8883);
while (!mqttClient.connected()) {
if (mqttClient.connect(deviceId.c_str(), (host + "/" + deviceId).c_str(), sasToken.c_str())) {
// Subscribe ke C2D messages
mqttClient.subscribe(("devices/" + deviceId + "/messages/devicebound/#").c_str());
// Subscribe ke direct methods
mqttClient.subscribe("$iothub/methods/POST/#");
// Subscribe ke twin changes
mqttClient.subscribe("$iothub/twin/PATCH/properties/desired/#");
} else {
delay(5000);
}
}
}
void publishTelemetry(float temp, float humidity) {
StaticJsonDocument<200> doc;
doc["temperature"] = temp;
doc["humidity"] = humidity;
char buffer[200];
serializeJson(doc, buffer);
String topic = "devices/sensor-01/messages/events/";
mqttClient.publish(topic.c_str(), buffer);
}
void loop() {
if (!mqttClient.connected()) connectAzure();
mqttClient.loop();
}
9. Quiz: Uji Pemahamanmu!
Setelah membaca tutorial di atas, jawablah 5 pertanyaan berikut untuk menguji pemahamanmu tentang Azure IoT Hub: