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.
- How To Create Azure IoT Hub Using PowerShell
- 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.
- 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.
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
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.
- 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).
- 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
- using System;
- using Microsoft.Azure.Devices.Client;
- using System.Text;
- using Newtonsoft.Json;
- using System.Threading.Tasks;
- namespace SimulationDeviceToCloud
- {
- class Program
- {
- private static DeviceClient s_deviceClient;
- private readonly static string s_connectionString01 = "HostName=HubflyIoTHubConnect.azure-devices.net;DeviceId=RaspberryPi;SharedAccessKey=b9g+mmjAV8SqBlv8o/TChP0WBFCL5wi8/pDccXzBoys=";
- static void Main(string[] args)
- {
- s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString01, TransportType.Mqtt);
- SendDeviceToCloudMessagesAsync(s_deviceClient);
- Console.ReadLine();
- }
- private static async void SendDeviceToCloudMessagesAsync(DeviceClient s_deviceClient)
- {
- try
- {
- double minTemperature = 20;
- double minHumidity = 60;
- Random rand = new Random();
- while (true)
- {
- double currentTemperature = minTemperature + rand.NextDouble() * 15;
- double currentHumidity = minHumidity + rand.NextDouble() * 20;
- // Create JSON message
- var telemetryDataPoint = new
- {
- temperature = currentTemperature,
- humidity = currentHumidity
- };
- string messageString = "";
- messageString = JsonConvert.SerializeObject(telemetryDataPoint);
- var message = new Message(Encoding.ASCII.GetBytes(messageString));
- // Add a custom application property to the message.
- // An IoT hub can filter on these properties without access to the message body.
- //message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false");
- // Send the telemetry message
- await s_deviceClient.SendEventAsync(message);
- Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
- await Task.Delay(1000 * 10);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- }
- }
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
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.
No comments:
Post a Comment