Azure

Machine To Cloud Communication Utilizing 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 trade between IoT purposes and gadgets. Azure IoT hub permits you to create dependable and safe communication between IoT gadgets and the Cloud app. The gadgets could be digital. It helps bi-directional communication i.e. from the system to the cloud and from the cloud to the system. On this article, I’ll clarify how are you going to ship the message from Cloud to Machine and Machine to Cloud.

 

Conditions

In my earlier article, I defined how one can create IoT Hub and Units. On this article, I’ll clarify how can we do gadgets to cloud communication and vice versa utilizing the IoT Hub. Right here, you’ll discover ways to ship telemetry from simulated system purposes to IoT Hub, and how are you going to learn messages ship by IoT Hub. I’ll clarify C2D (cloud to system) and D2C (system to cloud) communication utilizing the .NET app.

 

IoT hub connection string

You possibly can connect with the IoT Hub utilizing a connection string. You may get the connection string from “Shared entry insurance policies”. You possibly can view and modify the IoT hub shared entry insurance policies by clicking on the “Shared entry coverage” from the left panel beneath the setting part. There are some pre-defined shared entry insurance policies which are outlined. You possibly can add your customized shared entry coverage. Mainly, it accommodates the permission of IoT hub entry. Beneath the “Shared entry keys” part (proper facet), you discover connection strings.

 

 

Ship a cloud to system (C2D) message

Within the earlier part, you discovered about how are you going to get a connection string to attach with IoT Hub. The IoT hub entry proper is related to each shared entry coverage. To attach with IoT hub as a tool, the coverage should include “Service Join” entry.

 

The following step is to put in “Microsoft.Azure.Units” bundle utilizing Nuget bundle supervisor. You possibly can set up the required bundle by going to “Instruments >> Nuget Package deal Supervisor >> Handle Nuget Packages for answer”.

 

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

 

The “Microsoft.Azure.Units” namespace accommodates the ServiceClient class. This class accommodates strategies that helpful in sending a message to the system.

 

To create a ServiceClient class occasion, you need to use “ServiceClient.CreateFromConnectionString” methodology. This methodology creates a category occasion from the connection string. The tactic “SendAsync” of this class is used to ship messages to the system. This methodology accepts the system ID and message as a compulsory parameter. Following is an instance code to ship the message:

  1. static ServiceClient serviceClient;  
  2. static string connectionString = “{Connection string “;  
  3. static string deviceName = “Machine identify”;  
  4. static void Major(string[] args)  
  5. {  
  6.     Console.WriteLine(“=== Creating ServiceClient object utilizing Connection string! ===”);  
  7.     serviceClient = ServiceClient.CreateFromConnectionString(connectionString);  
  8.   
  9.     Console.WriteLine(“Press any key to ship knowledge to IOT Hub!”);  
  10.   
  11.       
  12.     Console.ReadLine();  
  13.   
  14.       
  15.     SendMessageToCloud().Wait();  
  16.              
  17.     Console.ReadLine();  
  18. }  
  19.   
  20. personal static async Activity SendMessageToCloud()  
  21. {  
  22.     MyData knowledge = new MyData { Id = “123”, Identify = “Jignesh Trivedi” };  
  23.     var serializeData = JsonConvert.SerializeObject(knowledge);  
  24.     var commandMessage = new Message(Encoding.ASCII.GetBytes(serializeData));  
  25.  
  26.     Console.WriteLine(“Ship Message: {0}”, serializeData);  
  27.     await serviceClient.SendAsync(deviceName, commandMessage);  
  28. }  
Device To Cloud Communication Using Azure IoT Hub In .NET Core

 

Obtain supply suggestions

Additionally it is attainable to request supply acknowledgment or expiration from the IoT hub for every C2D message. That is very helpful in callback mechanism the place you may simply write retry logic.

 

You may get a supply suggestions receiver object utilizing GetFeedbackReceiver methodology of ServiceClient. Utilizing methodology “FeedbackBatch.ReceiveAsync”, acknowledgment message could be obtained. By default, ReceiveAsync methodology is taken into account a default day trip however it’s also possible to specify timeout with this methodology.

  1. static void Major(string[] args)  
  2. {  
  3.     …  
  4.     …  
  5.     serviceClient = ServiceClient.CreateFromConnectionString(connectionString);  
  6.   
  7.       
  8.     ReceiveFeedbackAsync();  
  9.    …  
  10. }  
  1. personal async static void ReceiveFeedbackAsync()  
  2. {  
  3.     var feedbackReceiver = serviceClient.GetFeedbackReceiver();  
  4.   
  5.     Console.WriteLine(“nReceiving c2d suggestions from service”);  
  6.     whereas (true)  
  7.     {  
  8.         var feedbackBatch = await feedbackReceiver.ReceiveAsync();  
  9.         if (feedbackBatch == null) proceed;    
  10.         Console.WriteLine(“Acquired suggestions: {0}”,  
  11.             string.Be a part of(“, “, feedbackBatch.Data.Choose(f => f.StatusCode)));  
  12.   
  13.         await feedbackReceiver.CompleteAsync(feedbackBatch);  
  14.     }  
  15. }  

To request suggestions for acknowledgment for the C2D message, it’s a must to set Message.Ack to DeliveryAcknowledgement.Full earlier than sending the message.

  1. personal static async Activity 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

 

Obtain a Message from the Cloud

To obtain a message from the cloud, you must set up “Microsoft.Azure.Units.Consumer” bundle from NuGet. You possibly can set up the required bundle by going to “Instruments >> Nuget Package deal Supervisor >> Handle Nuget Packages for answer”.

 

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

 

The “Microsoft.Azure.Units.Consumer” namespace include DeviceClient class. This class accommodates strategies that helpful in sending/receiving messages and system twins messages to the system. You possibly can create DeviceClient class occasion both utilizing the hostname (“Create” methodology) or utilizing the connection string (“CreateFromConnectionString” methodology).

 

Utilizing “ReceiveAsync” methodology of DeviceClient, you may obtain the message from cloud to system.

  1. static DeviceClient deviceClient;  
  2. static string deviceConnectionString = “{Connection String”;  
  3.   
  4. static void Major(string[] args)  
  5. {  
  6.     deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString);  
  7.     ReceiveC2dAsync();  
  8.      
  9.     Console.Learn();  
  10. }  
  11.   
  12. personal static async void ReceiveC2dAsync()  
  13. {  
  14.     Console.WriteLine(“Receiving cloud to system messages from service”);  
  15.     whereas (true)  
  16.     {  
  17.         Message receivedMessage = await deviceClient.ReceiveAsync();  
  18.         if (receivedMessage == null) proceed;  
  19.     
  20.         Console.WriteLine(“Acquired message: {0}”,  
  21.         Encoding.ASCII.GetString(receivedMessage.GetBytes()));  
  22.   
  23.         await deviceClient.CompleteAsync(receivedMessage);  
  24.     }  
  25. }  

You possibly can ship messages to the system utilizing the ServiceClient object or from the Azure portal. To ship message to system utilizing portal, choose system from the record and click on on the “Message to system” button from the highest panel.

 

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

 

This redirects to message sends display screen and you may write a message to the “Message Physique” area and click on on the “Ship Message” button.

 

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

 

Sending messages from Machine to Cloud

You possibly can ship messages from the system to the cloud utilizing the SendEventAsync methodology of DeviceClient class. With this methodology, you may optionally cross the cancellation token.

  1. personal static async void SendD2CAsync()  
  2. {  
  3.     MyData knowledge = new MyData { Id = “123”, Identify = “Jignesh Trivedi” };  
  4.     var serializeData = JsonConvert.SerializeObject(knowledge);  
  5.     var commandMessage = new Message(Encoding.ASCII.GetBytes(serializeData));  
  6.               
  7.     Console.WriteLine(“Ship Message: {0}”, serializeData);  
  8.   
  9.     await deviceClient.SendEventAsync(commandMessage);  
  10. }  

You possibly can monitor/confirm D2C messages utilizing numerous instruments equivalent to Azure IoT instruments for VSCode, Cloud Explorer with Visual Studio, and many others. To view a D2C message utilizing Visual Studio, open “View >> Cloud Explorer”. Right here, you may view all IoT hubs that you just created utilizing the Visual Studio subscription account. Proper-click in your IoT hub or system and choose “Begin Monitoring Constructed-in Occasion EndPoint” or “Begin Receiving C2D Message” choices.

 

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

 

You possibly can monitor messages within the Output window.

 

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

 

Abstract

Azure IoT Hub is a managed service of Azure cloud which acts as a central bi-directional message hub to trade between IoT purposes and gadgets. It permits you to create dependable and safe options for connecting billions of gadgets. You need to use Azure IoT system SDK to construct system software program. It helps many languages equivalent to C, C#, Java, Python, and Node.js. This text explains how you can do C2D and D2C communication utilizing .web Azure IoT service SDK.

Tags
Show More

Related Articles

Leave a Reply

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

Close