Creating A Simulated Device For IoT Hub Using .NET

This article shows how to create a simulated device for IoT Hub using .NET

This article is in continuation of my previous article and here, I am going to create two console applications on the same project and use the Hostname and access keys to connect with these two applications that send the message to each other using the IoT hub that demonstrates the IoT connection between the two combined IoT devices.
 
Prerequisites
  • Read my previous article because it contains the device identity configuration.
  • Visual Studio 2015 or higher.
Follow the steps to create the console app on the Receiver device to cloud messages, In this, we are going to develop the console application that reads device's cloud information from IoT Hub.
 
Step 1

In Visual Studio, right-click the Solution Explorer followed by click on "Add" >> "New Project." 

 
 
Step 2

Open the Console App (.NET Framework) and enter the desired name for our project. Press OK.

 

Now, the Solution Explorer consists of two projects.

Step 3

For our project, we need to add some packages. In the Browse window, search for the WindowsAzure.ServiceBus and press Install.

 

Step 4

Copy and replace the code in the Program.cs of the desired project that you created, i.e., the second one and save the project. Paste the connection string on the 13th line of your code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.ServiceBus.Messaging;  
  7. using System.Threading;  
  8.   
  9. namespace DemoReadDeviceToCloudMessages  
  10. {  
  11.     class Program  
  12.     {  
  13.         static string connectionString = "{iothub connection string}";  
  14.         static string iotHubD2cEndpoint = "messages/events";  
  15.         static EventHubClient eventHubClient;  
  16.         private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)  
  17.         {  
  18.             var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);  
  19.             while (true)  
  20.             {  
  21.                 if (ct.IsCancellationRequested) break;  
  22.                 EventData eventData = await eventHubReceiver.ReceiveAsync();  
  23.                 if (eventData == nullcontinue;  
  24.   
  25.                 string data = Encoding.UTF8.GetString(eventData.GetBytes());  
  26.                 Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);  
  27.             }  
  28.         }  
  29.         static void Main(string[] args)  
  30.         {  
  31.             Console.WriteLine("Receive messages. Ctrl-C to exit.\n");  
  32.             eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);  
  33.   
  34.             var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;  
  35.   
  36.             CancellationTokenSource cts = new CancellationTokenSource();  
  37.   
  38.             System.Console.CancelKeyPress += (s, e) =>  
  39.             {  
  40.                 e.Cancel = true;  
  41.                 cts.Cancel();  
  42.                 Console.WriteLine("Exiting...");  
  43.             };  
  44.   
  45.             var tasks = new List<Task>();  
  46.             foreach (string partition in d2cPartitions)  
  47.             {  
  48.                 tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));  
  49.             }  
  50.             Task.WaitAll(tasks.ToArray());  
  51.         }  
  52.     }  
  53. }  
It's time to create the simulated device that sends a device to cloud messages to an IoT Hub.

Step 5

Again, in the same project, add the new console application and name the application as DemoSimulatedDevice. Press OK to create the program.Now, our Solution Explorer consists of three projects.

 

Step 6

For this project we need some packages. Adding the required packages through the NuGet package. In browse field, search for Microsoft.Azure.Devices.Client and press Install.



Step-7

Copy and replace the code in the Program.cs of the desired project that you created the second one and save the project.Replace the 14th line with Hostname that is taken from the Azure portal and the 15th one is take from the device identity of my previous article.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.Azure.Devices.Client;  
  7. using Newtonsoft.Json;  
  8.   
  9. namespace DemoIOTSimulatedDevice  
  10. {  
  11.     class Program  
  12.     {  
  13.         static DeviceClient deviceClient;  
  14.         static string iotHubUri = "{iot hub hostname}";  
  15.         static string deviceKey = "{device key}";  
  16.         private static async void SendDeviceToCloudMessagesAsync()  
  17.         {  
  18.             double minTemperature = 20;  
  19.             double minHumidity = 60;  
  20.             int messageId = 1;  
  21.             Random rand = new Random();  
  22.   
  23.             while (true)  
  24.             {  
  25.                 double currentTemperature = minTemperature + rand.NextDouble() * 15;  
  26.                 double currentHumidity = minHumidity + rand.NextDouble() * 20;  
  27.   
  28.                 var telemetryDataPoint = new  
  29.                 {  
  30.                     messageId = messageId++,  
  31.                     deviceId = "myFirstDevice",  
  32.                     temperature = currentTemperature,  
  33.                     humidity = currentHumidity  
  34.                 };  
  35.                 var messageString = JsonConvert.SerializeObject(telemetryDataPoint);  
  36.                 var message = new Message(Encoding.ASCII.GetBytes(messageString));  
  37.                 message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false");  
  38.   
  39.                 await deviceClient.SendEventAsync(message);  
  40.                 Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);  
  41.   
  42.                 await Task.Delay(1000);  
  43.             }  
  44.         }  
  45.         static void Main(string[] args)  
  46.         {  
  47.             Console.WriteLine("DemoIOTSimulated device\n");  
  48.             deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("myFirstDevice", deviceKey), TransportType.Mqtt);  
  49.   
  50.             SendDeviceToCloudMessagesAsync();  
  51.             Console.ReadLine();  
  52.         }  
  53.     }  
  54. }  
Step-8

Save the application and then we are going to run the application simultaneously.So follow the steps to configure the execution of the multiple projects.

 

Right-click the 
Solution Explorer and choose the Set Startup projects and choose the two projects to Start action.Finally, Press Ok to save the multiple Startup projects.

 
 
Step-9

Press Start or F5 to start both the apps to Execute.The Console Output from the DemoSimulatedDevice displays the messages of our device app sends to the IoT Hub, and again the console output from the DemoReadDeviceToCloudMsgs app gets the message for the IoT Hub and shows as the Output.

 

Step-10

Finally, In the portal on our IoT hub, the Usage tile shows the number of messages sent to the IoT hubs,



Summary

I hope that you understood how to create and simulate the devices for IoT and how it works can be demonstrated in this article and also the message is sent to the IoT Hub and the IoT Hub again sends back to simulated to the device to show the output.