Azure IoT Hub를 이용한 장치-클라우드 및 클라우드-장치 통신

Azure IoT Hub에 장치를 등록하고 고유 식별자를 얻는 방법을 이전 글에서 살펴보았습니다.

이번에는 장치에서 클라우드로 그리고 클라우드에서 장치로의 메시지 전송 방법을 알아보겠습니다.

1. Azure IoT Hub에서 장치로부터의 메시지 수신

AMQP 프로토콜을 사용하여 Event Hub 호환 엔드포인트에서 장치에서 클라우드로의 메시지를 읽습니다.

새로운 콘솔 프로젝트 'IoTHubReceiver'를 생성하고, NuGet 패키지 'Azure.Messaging.EventHubs'를 추가합니다.

필요한 네임스페이스: using Azure.Messaging.EventHubs;

중요 클래스: EventHubConsumerClient

다음은 메시지를 수신하는 코드 예제입니다.

string connectionString = "Endpoint=sb://iothubnamespace.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=yourkey";
string eventHubName = "eventhubname";
EventHubConsumerClient consumerClient;

public async Task ReceiveMessages()
{
    consumerClient = new EventHubConsumerClient(EventHubConsumerClient.DefaultConsumerGroupName, connectionString, eventHubName);
    
    await foreach (PartitionEvent partitionEvent in consumerClient.ReadEventsAsync())
    {
        string data = Encoding.UTF8.GetString(partitionEvent.Data.Body.ToArray());
        Console.WriteLine($"Message received. Partition: {partitionEvent.Partition.PartitionId} Data: '{data}'");
        
        await Task.Delay(1);
    }
}

Main 함수에서는 IoTHubReceiver를 실행합니다:

static void Main(string[] args)
{
    Console.WriteLine("Azure IoT Hub에서 메시지 수신 중... Ctrl-C를 눌러 종료\n");
    var consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;
    var consumerClient = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName);

    CancellationTokenSource cts = new CancellationTokenSource();
    Console.CancelKeyPress += (s, e) =>
    {
        e.Cancel = true;
        cts.Cancel();
        Console.WriteLine("종료 중...");
    };

    Task receiveTask = ReceiveMessages();
    receiveTask.Wait(cts.Token);
}

2. 장치에서 Azure IoT Hub로 메시지 보내기

장치에서 메시지를 보내기 위한 새로운 콘솔 프로젝트 'DeviceSender'를 만듭니다. 필요한 NuGet 패키지는 'Microsoft.Azure.Devices.Client'.

사용할 네임스페이스: using Microsoft.Azure.Devices.Client; using Newtonsoft.Json;

핵심 클래스: Microsoft.Azure.Devices.Client.DeviceClient

장치 키와 IoT Hub 호스트 이름을 사용하여 메시지를 보냅니다.

static DeviceClient deviceClient;
static string iotHubUri = "iothubnamespace.azure-devices.net";
static string deviceKey = "yourdevicekey";

async void SendMessageToCloud()
{
    Random rand = new Random();
    double avgWindSpeed = 10; 

    while (true)
    {
        double currentWindSpeed = avgWindSpeed + rand.NextDouble() * 4 - 2;
        var telemetryData = new
        {
            deviceId = "Device001",
            windSpeed = currentWindSpeed
        };
        var messageString = JsonConvert.SerializeObject(telemetryData);
        var message = new Message(Encoding.ASCII.GetBytes(messageString));

        await deviceClient.SendEventAsync(message);
        Console.WriteLine($"{DateTime.Now} > 메시지 전송: {messageString}");

        await Task.Delay(1000);
    }
}

Main 함수에서 메시지 전송을 시작합니다:

static void Main(string[] args)
{
    Console.WriteLine("장치 메시지 전송...\n");
    deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("Device001", deviceKey), TransportType.Mqtt);

    SendMessageToCloud();
    Console.ReadLine();
}

3. 실행 및 테스트

솔루션 설정에서 두 개의 시작 프로젝트(DeviceSender, IoTHubReceiver)를 선택하고 F5를 눌러 실행합니다.

Azure Portal에서 통계를 확인하면, 장치에서 클라우드로의 메시지 전송과 수신이 정상적으로 이루어지고 있음을 확인할 수 있습니다.

태그: Azure IoT EventHub DeviceCommunication

7월 3일 16:27에 게시됨