Dashboard & Cloud

Azure IoT Hub untuk Device Management

Tutorial lengkap Azure IoT Hub. Pelajari device twins, direct methods, file upload, message routing, dan Device Provisioning Service (DPS) dari nol hingga mahir.

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).

💡 Tips

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

FiturDeskripsi
Device-to-Cloud (D2C)Device mengirim telemetry ke cloud
Cloud-to-Device (C2D)Cloud mengirim message/command ke device
Device TwinsJSON document sinkronisasi state (tag, desired, reported)
Direct MethodsInvoke fungsi langsung di device (RPC)
File UploadUpload file dari device ke Azure Blob Storage
Message RoutingRoute message berdasarkan filter ke berbagai endpoint
DPSZero-touch device provisioning
IoT EdgeRuntime untuk workload di edge device

Azure IoT Hub vs AWS IoT Core

AspekAzure IoT HubAWS IoT Core
State SyncDevice TwinsDevice Shadow
RPCDirect MethodsMQTT + Jobs
File UploadBuilt-in (ke Blob Storage)Manual (via S3 presigned URL)
ProvisioningDPS (terpisah)Fleet Provisioning (built-in)
ProtokolMQTT, AMQP, HTTPSMQTT, HTTPS
Pricing ModelPer message tierPer 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

EndpointKegunaan
Event HubStreaming data real-time (seperti Kafka)
Service Bus Queue/TopicMessage queue untuk processing
Blob StorageArchive data (JSON/CSV/AVRO)
Cosmos DBNoSQL database untuk telemetry
Custom EndpointAzure 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:

Pertanyaan 1: Apa fungsi Device Twins di Azure IoT Hub?

a) Mengenkripsi komunikasi
b) JSON document untuk sinkronisasi state device (desired, reported, tags)
c) Mengelola firmware update
d) Menyimpan log device

Pertanyaan 2: Apa yang dilakukan Direct Methods?

a) Mengirim email ke device
b) Memanggil fungsi langsung di device (RPC) dan mendapatkan response
c) Meng-upload file ke cloud
d) Mengelola koneksi WiFi device

Pertanyaan 3: File Upload di Azure IoT Hub menggunakan...

a) MQTT untuk mengirim file langsung
b) FTP protocol
c) SAS URI dari IoT Hub, lalu upload langsung ke Azure Blob Storage
d) HTTP POST ke IoT Hub

Pertanyaan 4: Apa fungsi Message Routing di IoT Hub?

a) Mengelola koneksi device
b) Mengarahkan device messages ke berbagai Azure service berdasarkan filter query
c) Menyimpan data telemetry
d) Mengelola sertifikat device

Pertanyaan 5: Apa keunggulan Device Provisioning Service (DPS)?

a) Zero-touch provisioning — device dialokasikan ke IoT Hub tanpa hardcoding
b) Menyediakan free tier unlimited
c) Menggantikan IoT Hub
d) Hanya untuk device Raspberry Pi
← SebelumnyaAWS IoT Core Selanjutnya →Node-RED Advanced
🔍 Zoom
100%
🎨 Tema