How To Send Telemetry From An IoT Device To The Azure IoT Hub Using C#

Introduction

 
In this article, we are going to see how to send telemetry from an IoT device to the Azure IoT Hub using C#. IoT Hub is a cloud platform to securely connect billions of IoT devices to create IoT applications. Please read the previous parts of the article before continuing with this one.
  1. How To Create Azure IoT Hub Using PowerShell
  2. How to Register IoT Device in Azure IoT Hub Using PowerShell
Creating a C# Console Application
  • Open Visual Studio, go to File -> New -> and select Project.
How To Send Telemetry From An IoT Device To The Azure IoT Hub Using C#
  • In Templates, select Visual C#, select Console App (.NET Framework) and give an appropriate name in the ‘Name’ textbox and then click the OK button.
How To Send Telemetry From An IoT Device To The Azure IoT Hub Using C#
 
Installing Microsoft Azure IoT Device Client SDK
  • Go to Project -> Manage NuGet Packages.
  • Click Browse tab and search for Microsoft.Azure.Devices.Client. You will see the Microsoft.Azure.Devices.Client device SDK will have listed in the search result and click Install button
  • Now, click the I Accept button to accept the license agreement.
  • It will take a few minutes to install the SDK in our project
How To Send Telemetry From An IoT Device To The Azure IoT Hub Using C#
 
Get IoT device connect string from Azure IoT Hub
  • Open your Azure portal and choose your IoT Hub.
  • Click IoT devices In Explorers. You can see the list of devices that are connected to the IoT Hub.
How To Send Telemetry From An IoT Device To The Azure IoT Hub Using C#
  • Double click the device, you can see the device detailed information like device id, Primary Key, Secondary Key, Connection String(primary key) and Connection String (secondary key).
How To Send Telemetry From An IoT Device To The Azure IoT Hub Using C# 
  • Using Microsoft.Azure.Devices.Client library we can create device client. The device client has CreateFromConnectionString method which requires device connection string as parameter. Create a read only static string s_connectionString01 and assign the connection string that we copy from Azure Portal.
  • Here you can create a random temperature and humidity values using Random() method.
  • Now open the program.cs file and type the below code 
  1. using System;  
  2. using Microsoft.Azure.Devices.Client;  
  3. using System.Text;  
  4. using Newtonsoft.Json;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace SimulationDeviceToCloud  
  8. {  
  9.     class Program  
  10.     {  
  11.         private static DeviceClient s_deviceClient;  
  12.         private readonly static string s_connectionString01 = "HostName=HubflyIoTHubConnect.azure-devices.net;DeviceId=RaspberryPi;SharedAccessKey=b9g+mmjAV8SqBlv8o/TChP0WBFCL5wi8/pDccXzBoys=";  
  13.         static void Main(string[] args)  
  14.         {  
  15.             s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString01, TransportType.Mqtt);  
  16.             SendDeviceToCloudMessagesAsync(s_deviceClient);  
  17.             Console.ReadLine();  
  18.   
  19.         }  
  20.   
  21.         private static async void SendDeviceToCloudMessagesAsync(DeviceClient s_deviceClient)  
  22.         {  
  23.             try  
  24.             {  
  25.                 double minTemperature = 20;  
  26.                 double minHumidity = 60;  
  27.                 Random rand = new Random();  
  28.   
  29.                 while (true)  
  30.                 {  
  31.                     double currentTemperature = minTemperature + rand.NextDouble() * 15;  
  32.                     double currentHumidity = minHumidity + rand.NextDouble() * 20;  
  33.   
  34.                    // Create JSON message  
  35.   
  36.                     var telemetryDataPoint = new  
  37.                     {  
  38.                          
  39.                         temperature = currentTemperature,  
  40.                         humidity = currentHumidity  
  41.                     };  
  42.   
  43.                     string messageString = "";  
  44.   
  45.   
  46.   
  47.                     messageString = JsonConvert.SerializeObject(telemetryDataPoint);  
  48.   
  49.                     var message = new Message(Encoding.ASCII.GetBytes(messageString));  
  50.   
  51.                     // Add a custom application property to the message.  
  52.                     // An IoT hub can filter on these properties without access to the message body.  
  53.                     //message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false");  
  54.   
  55.                     // Send the telemetry message  
  56.                     await s_deviceClient.SendEventAsync(message);  
  57.                     Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);  
  58.                     await Task.Delay(1000 * 10);  
  59.                   
  60.                 }  
  61.             }  
  62.             catch (Exception ex)  
  63.             {  
  64.   
  65.                 throw ex;  
  66.             }  
  67.         }  
  68.     }  
  69. }  
  70.  
That's it. Now, run the web application, go to Debug menu, and click on "Start without Debugging" or press F5. This will display the below result
 
How To Send Telemetry From An IoT Device To The Azure IoT Hub Using C#
 
I hope you have learned how to send telemetry from an IoT device to an Azure IoT Hub using C#. Feel free to fill up the comment box below if you need any further assistance from us.