Device To Cloud Communication Using Azure IoT Hub In .NET Core

Introduction

 
Azure IoT Hub is a managed service of Azure cloud which acts as a central bi-directional message hub to exchange between IoT applications and devices. Azure IoT hub allows you to create reliable and secure communication between IoT devices and the Cloud app. The devices can be virtual. It supports bi-directional communication i.e. from the device to the cloud and from the cloud to the device. In this article, I will explain how can you send the message from Cloud to Device and Device to Cloud.
 
Prerequisites
In my previous article, I explained how you can create IoT Hub and Devices. In this article, I will explain how can we do devices to cloud communication and vice versa using the IoT Hub. Here, you will learn how to send telemetry from simulated device applications to IoT Hub, and how can you read messages send by IoT Hub. I will explain C2D (cloud to device) and D2C (device to cloud) communication using the .NET app.
 

IoT hub connection string


You can connect to the IoT Hub using a connection string. You can get the connection string from "Shared access policies". You can view and modify the IoT hub shared access policies by clicking on the "Shared access policy" from the left panel under the setting section. There are some pre-defined shared access policies that are defined. You can add your custom shared access policy. Basically, it contains the permission of IoT hub access. Under the "Shared access keys" section (right side), you find connection strings.
 
Device To Cloud Communication Using Azure IoT Hub In .NET Core
 

Send a cloud to device (C2D) message


In the earlier section, you learned about how can you get a connection string to connect with IoT Hub. The IoT hub access right is associated with every shared access policy. To connect with IoT hub as a device, the policy must contain "Service Connect" access.
 
The next step is to install "Microsoft.Azure.Devices" package using Nuget package manager. You can install the required package by going to "Tools >> Nuget Package Manager >> Manage Nuget Packages for solution".
 
Device To Cloud Communication Using Azure IoT Hub In .NET Core
 
The "Microsoft.Azure.Devices" namespace contains the ServiceClient class. This class contains methods that useful in sending a message to the device.
 
To create a ServiceClient class instance, you can use "ServiceClient.CreateFromConnectionString" method. This method creates a class instance from the connection string. The method "SendAsync" of this class is used to send messages to the device. This method accepts the device ID and message as a mandatory parameter. Following is an example code to send the message:
  1. static ServiceClient serviceClient;  
  2. static string connectionString = "{Connection string ";  
  3. static string deviceName = "Device name";  
  4. static void Main(string[] args)  
  5. {  
  6.     Console.WriteLine("=== Creating ServiceClient object using Connection string! ===");  
  7.     serviceClient = ServiceClient.CreateFromConnectionString(connectionString);  
  8.   
  9.     Console.WriteLine("Press any key to send data to IOT Hub!");  
  10.   
  11.     //Waiting for press any key  
  12.     Console.ReadLine();  
  13.   
  14.     //Send message to IoT Hub  and wait until the message sent  
  15.     SendMessageToCloud().Wait();  
  16.              
  17.     Console.ReadLine();  
  18. }  
  19.   
  20. private static async Task SendMessageToCloud()  
  21. {  
  22.     MyData data = new MyData { Id = "123", Name = "Jignesh Trivedi" };  
  23.     var serializeData = JsonConvert.SerializeObject(data);  
  24.     var commandMessage = new Message(Encoding.ASCII.GetBytes(serializeData));  
  25.  
  26.     Console.WriteLine("Send Message: {0}", serializeData);  
  27.     await serviceClient.SendAsync(deviceName, commandMessage);  
  28. }  
Device To Cloud Communication Using Azure IoT Hub In .NET Core
 

Receive delivery feedback


It is also possible to request delivery acknowledgment or expiration from the IoT hub for each C2D message. This is very useful in callback mechanism where you can easily write retry logic.
 
You can get a delivery feedback receiver object using GetFeedbackReceiver method of ServiceClient. Using method "FeedbackBatch.ReceiveAsync", acknowledgment message can be received. By default, ReceiveAsync method is considered a default time out but you can also specify timeout with this method.
  1. static void Main(string[] args)  
  2. {  
  3.     ...  
  4.     ...  
  5.     serviceClient = ServiceClient.CreateFromConnectionString(connectionString);  
  6.   
  7.     //Create Feedback receiver that continuous monitor for feedback  
  8.     ReceiveFeedbackAsync();  
  9.    ...  
  10. }  
  1. private async static void ReceiveFeedbackAsync()  
  2. {  
  3.     var feedbackReceiver = serviceClient.GetFeedbackReceiver();  
  4.   
  5.     Console.WriteLine("\nReceiving c2d feedback from service");  
  6.     while (true)  
  7.     {  
  8.         var feedbackBatch = await feedbackReceiver.ReceiveAsync();  
  9.         if (feedbackBatch == null) continue;    
  10.         Console.WriteLine("Received feedback: {0}",  
  11.             string.Join(", ", feedbackBatch.Records.Select(f => f.StatusCode)));  
  12.   
  13.         await feedbackReceiver.CompleteAsync(feedbackBatch);  
  14.     }  
  15. }  
To request feedback for acknowledgment for the C2D message, you have to set Message.Ack to DeliveryAcknowledgement.Full before sending the message.
  1. private static async Task SendMessageToCloud()  
  2. {  
  3.    ...  
  4.    ...  
  5.     var commandMessage = new Message(Encoding.ASCII.GetBytes(serializeData));  
  6.     commandMessage.Ack = DeliveryAcknowledgement.Full;  
  7.   
  8.     ...  
  9.    ....  
  10. }  
Device To Cloud Communication Using Azure IoT Hub In .NET Core
 

Receive a Message from the Cloud


To receive a message from the cloud, you need to install "Microsoft.Azure.Devices.Client" package from NuGet. You can install the required package by going to "Tools >> Nuget Package Manager >> Manage Nuget Packages for solution".
 
Device To Cloud Communication Using Azure IoT Hub In .NET Core 
 
The "Microsoft.Azure.Devices.Client" namespace contain DeviceClient class. This class contains methods that useful in sending/receiving messages and device twins messages to the device. You can create DeviceClient class instance either using the hostname ("Create" method) or using the connection string ("CreateFromConnectionString" method).
 
Using "ReceiveAsync" method of DeviceClient, you can receive the message from cloud to device.
  1. static DeviceClient deviceClient;  
  2. static string deviceConnectionString = "{Connection String";  
  3.   
  4. static void Main(string[] args)  
  5. {  
  6.     deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString);  
  7.     ReceiveC2dAsync();  
  8.      
  9.     Console.Read();  
  10. }  
  11.   
  12. private static async void ReceiveC2dAsync()  
  13. {  
  14.     Console.WriteLine("Receiving cloud to device messages from service");  
  15.     while (true)  
  16.     {  
  17.         Message receivedMessage = await deviceClient.ReceiveAsync();  
  18.         if (receivedMessage == null) continue;  
  19.     
  20.         Console.WriteLine("Received message: {0}",  
  21.         Encoding.ASCII.GetString(receivedMessage.GetBytes()));  
  22.   
  23.         await deviceClient.CompleteAsync(receivedMessage);  
  24.     }  
  25. }  
You can send messages to the device using the ServiceClient object or from the Azure portal. To send message to device using portal, select device from the list and click on the "Message to device" button from the top panel.
 
Device To Cloud Communication Using Azure IoT Hub In .NET Core
 
This redirects to message sends screen and you can write a message to the "Message Body" field and click on the "Send Message" button.
 
Device To Cloud Communication Using Azure IoT Hub In .NET Core
 

Sending messages from Device to Cloud


You can send messages from the device to the cloud using the SendEventAsync method of DeviceClient class. With this method, you can optionally pass the cancellation token.
  1. private static async void SendD2CAsync()  
  2. {  
  3.     MyData data = new MyData { Id = "123", Name = "Jignesh Trivedi" };  
  4.     var serializeData = JsonConvert.SerializeObject(data);  
  5.     var commandMessage = new Message(Encoding.ASCII.GetBytes(serializeData));  
  6.               
  7.     Console.WriteLine("Send Message: {0}", serializeData);  
  8.   
  9.     await deviceClient.SendEventAsync(commandMessage);  
  10. }  
You can monitor/verify D2C messages using various tools such as Azure IoT tools for VSCode, Cloud Explorer with Visual Studio, etc. To view a D2C message using Visual Studio, open "View >> Cloud Explorer". Here, you can view all IoT hubs that you created using the Visual Studio subscription account. Right-click on your IoT hub or device and select "Start Monitoring Built-in Event EndPoint" or "Start Receiving C2D Message" options.
 
Device To Cloud Communication Using Azure IoT Hub In .NET Core
 
You can monitor messages in the Output window.
 
Device To Cloud Communication Using Azure IoT Hub In .NET Core
 

Summary


Azure IoT Hub is a managed service of Azure cloud which acts as a central bi-directional message hub to exchange between IoT applications and devices. It allows you to create reliable and secure solutions for connecting billions of devices. You can use Azure IoT device SDK to build device software. It supports many languages such as C, C#, Java, Python, and Node.js. This article explains how to do C2D and D2C communication using .net Azure IoT service SDK.