Azure IoT – “cloud to device”

Azure IoT – Cihaz simülasyonu ile uygulamalar 3

Merhaba,

Uygulamalar 1 paylaşımının üzerine devam eden bu uygulamada, IoT hub’dan(backend solution’dan) bir nesneye mesaj gönderilmesini ve geri bildirimini inceleyeceğiz. Dokümantasyon adresini kaynaklar kısmında paylaştım.

Uygulama 1 ‘de oluşturulan nesne simülasyonunun kodunu aşağıdaki ile güncelleyelim.

 

using Microsoft.Azure.Devices.Client;

using Newtonsoft.Json;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace SimulatedDevice

{

    class Program

    {

        static DeviceClient deviceClient;

        static string iotHubUri = "iotlab001.azure-devices.net";

        static string deviceKey = "+NGcYj37VUUNQXBkdvtX1XneP6+LZGQdK/liZwlQjWc=";

 

        private static async void SendDeviceToCloudMessagesAsync()

        {

            double minTemperature = 20;

            double minHumidity = 60;

            Random rand = new Random();

 

            while (true)

            {

                double currentTemperature = minTemperature + rand.NextDouble() * 15;

                double currentHumidity = minHumidity + rand.NextDouble() * 20;

 

                var telemetryDataPoint = new

                {

                    deviceId = "myFirstDevice",

                    temperature = currentTemperature,

                    humidity = currentHumidity

                };

                var messageString = JsonConvert.SerializeObject(telemetryDataPoint);

                string levelValue;

 

                if (rand.NextDouble() > 0.7)

                {

                    messageString = "This is a critical message";

                    levelValue = "critical";

                }

                else

                {

                    levelValue = "normal";

                }

 

                var message = new Message(Encoding.ASCII.GetBytes(messageString));

                message.Properties.Add("level", levelValue);

 

                await deviceClient.SendEventAsync(message);

                Console.WriteLine("{0} > Sent message: {1}", DateTime.Now, messageString);

 

                await Task.Delay(1000);

            }

        }

        private static async void ReceiveC2dAsync()

        {

            Console.WriteLine("\nReceiving cloud to device messages from service");

            while (true)

            {

                Message receivedMessage = await deviceClient.ReceiveAsync();

                if (receivedMessage == null) continue;

 

                Console.ForegroundColor = ConsoleColor.Yellow;

                Console.WriteLine("Received message: {0}", Encoding.ASCII.GetString(receivedMessage.GetBytes()));

                Console.ResetColor();

 

                await deviceClient.CompleteAsync(receivedMessage);

            }

        }

        static void Main(string[] args)

        {

            Console.WriteLine("Simulated device\n");

            deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("myFirstDevice", deviceKey), TransportType.Mqtt);

 

            SendDeviceToCloudMessagesAsync();

            ReceiveC2dAsync();

            Console.ReadLine();

        }

    }

}

 

 

ReceiveC2dAsync() metodu eklenmiş oldu. Metod, cihaza ulaşan mesajı döndürüyor.

Cloud to Device için de mevcut solution’a yeni bir project ekliyoruz. Project’in ismi SendCloudToDevice , nuget paket yöneticisinden microsoft.azure.devices paketini yüklüyoruz.

 

 

using Microsoft.Azure.Devices;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace SendCloudToDevice

{

    class Program

    {

        static ServiceClient serviceClient;

        static string connectionString = "HostName=iotlab001.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=7i+GZgxyytt1dzhNDq014GzrHTiiiiiLzHZ7NniAw5Lps=";

        private async static Task SendCloudToDeviceMessageAsync()

        {

            var commandMessage = new Message(Encoding.ASCII.GetBytes("Cloud to device message."));

            await serviceClient.SendAsync("myFirstDevice", commandMessage);

        }

        static void Main(string[] args)

        {

            Console.WriteLine("Send Cloud-to-Device message\n");

            serviceClient = ServiceClient.CreateFromConnectionString(connectionString);

 

            Console.WriteLine("Press any key to send a C2D message.");

            Console.ReadLine();

            SendCloudToDeviceMessageAsync().Wait();

            Console.ReadLine();

        }

    }

}

 

Startup için aşağıdaki project’leri start moduna alıyoruz.  

  • ReadDeviceToCloudMessages

  • SimulatedDevice

  • SendCloudToDevice

 

Solution’ı çalıştıralım.

 

Cloud to Device application’ında bir key’e tıklayıp ilerlettiğimizde cloud to device tag’li mesajı nesne simülasyonunda görüyoruz(nesne simülasyonuna yeni bir metod eklemiştik)

Delivery feedback için kaynaklar kısmında paylaştığım dokümantasyonu inceleyebilirsiniz.

 

Kaynaklar:

https://msdn.microsoft.com/library/hh680901(v=pandp.50).aspx 

https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-process-d2c

https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *