This guide provides step-by-step instructions on how to establish a secure and reliable connection between your Windows IoT devices and Azure IoT Hub.
If you haven't already, create an Azure IoT Hub instance. Within your IoT Hub, register a new device. This will provide you with a unique Device ID and an Primary or Secondary key. You will use these to construct your device's connection string.
Note: Keep your IoT Hub connection string and device keys secure. Do not commit them directly into your source code.
The device connection string uniquely identifies your device to IoT Hub. It typically follows this format:
HostName=;DeviceId=;SharedAccessKey=
You can find the necessary components for this string in the Azure portal under your IoT Hub's "Devices" section, by selecting your registered device.
For this tutorial, we'll use a simple C# Universal Windows Platform (UWP) application.
IoTHubConnector) and choose a location.Microsoft.Azure.Devices.Client.
Open your MainPage.xaml.cs file and add the following code. This example demonstrates sending a telemetry message.
using System;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Microsoft.Azure.Devices.Client; // Required for DeviceClient
// For telemetry data structure
using System.Collections.Generic;
namespace IoTHubConnector
{
public sealed partial class MainPage : Page
{
// Replace with your actual device connection string
private const string DeviceConnectionString = "YOUR_DEVICE_CONNECTION_STRING";
private DeviceClient deviceClient;
public MainPage()
{
this.InitializeComponent();
Loaded += MainPage_Loaded;
}
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
await InitializeDeviceClient();
SendTelemetryButton.Click += SendTelemetryButton_Click; // Assuming you have a button named SendTelemetryButton in XAML
}
private async Task InitializeDeviceClient()
{
try
{
deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString, TransportType.Mqtt);
await deviceClient.OpenAsync();
StatusTextBlock.Text = "Device client initialized and connected to IoT Hub."; // Assuming a TextBlock named StatusTextBlock
}
catch (Exception ex)
{
StatusTextBlock.Text = $"Error initializing device client: {ex.Message}";
}
}
private async void SendTelemetryButton_Click(object sender, RoutedEventArgs e)
{
if (deviceClient == null)
{
StatusTextBlock.Text = "Device client is not connected.";
return;
}
try
{
var telemetryData = new
{
messageId = Guid.NewGuid().ToString(),
deviceId = "myWindowsIoTDevice", // Should match your device ID
temperature = 25.5,
humidity = 60.2,
timestamp = DateTime.UtcNow
};
string messageString = Newtonsoft.Json.JsonConvert.SerializeObject(telemetryData);
var message = new Message(Encoding.UTF8.GetBytes(messageString));
// Add custom application properties if needed
message.Properties.Add("sensorType", "environment");
await deviceClient.SendEventAsync(message);
StatusTextBlock.Text = $"Telemetry message sent: {messageString}";
}
catch (Exception ex)
{
StatusTextBlock.Text = $"Error sending telemetry: {ex.Message}";
}
}
// Important: Close the client when the application is closing
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
deviceClient?.CloseAsync().Wait(); // Use Wait() for simplicity in UWP for blocking close
base.OnNavigatingFrom(e);
}
}
}
Make sure to replace YOUR_DEVICE_CONNECTION_STRING with the actual connection string obtained in Step 2.
You will also need to add the Newtonsoft.Json NuGet package for JSON serialization.
In MainPage.xaml, you might want to add a Button and a TextBlock for status updates:
<Page
x:Class="IoTHubConnector.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:IoTHubConnector"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid Padding="20">
<StackPanel Spacing="15" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock x:Name="StatusTextBlock" Text="Initializing..." Style="{StaticResource BodyTextBlockStyle}" TextWrapping="Wrap"/>
<Button x:Name="SendTelemetryButton" Content="Send Telemetry" HorizontalAlignment="Center"/>
</StackPanel>
</Grid>
</Page>
Configure your project to target your Windows IoT device. You can typically do this by setting the "Target device" in the project properties to "Remote Machine" and providing the IP address of your device.
Once deployed and running, you should see the status update in the StatusTextBlock, and clicking the "Send Telemetry" button will send data to your Azure IoT Hub.
Tip: For a production environment, consider using Azure IoT Device Provisioning Service (DPS) for zero-touch provisioning of your devices.