This tutorial walks you through setting up MQTT communication on a Windows IoT device using .NET and the M2Mqtt library.
Open Visual Studio, create a new Blank App (Universal Windows) project, and name it IoTMqttDemo.
Install-Package M2Mqtt -Version 4.3.0
Replace the contents of MainPage.xaml.cs with the code below. It connects to the broker, subscribes to a topic, and publishes a message every 5 seconds.
using System;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace IoTMqttDemo
{
public sealed partial class MainPage : Page
{
private MqttClient _client;
private const string BrokerAddress = "broker.hivemq.com";
private const string Topic = "windows/iot/demo";
public MainPage()
{
this.InitializeComponent();
Loaded += MainPage_Loaded;
}
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
await ConnectMqttAsync();
}
private Task ConnectMqttAsync()
{
return Task.Run(() =>
{
_client = new MqttClient(BrokerAddress);
_client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
string clientId = Guid.NewGuid().ToString();
_client.Connect(clientId);
_client.Subscribe(new[] { Topic }, new[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
// Publish a heartbeat message
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer.Tick += (s, e) =>
{
string payload = $"{{ \"timestamp\": \"{DateTime.UtcNow:o}\" }}";
_client.Publish(Topic, Encoding.UTF8.GetBytes(payload));
};
timer.Start();
});
}
private async void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
string message = Encoding.UTF8.GetString(e.Message);
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
ReceivedTextBlock.Text = $"Received: {message}";
});
}
}
}
Add a simple UI to MainPage.xaml to display incoming messages.
<Page
x:Class="IoTMqttDemo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:IoTMqttDemo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Text="MQTT Demo – Windows IoT" FontSize="24" FontWeight="Bold" Margin="0,0,0,20"/>
<TextBlock x:Name="ReceivedTextBlock" Text="Waiting for data..." FontSize="16"/>
</StackPanel>
</Grid>
</Page>
Device Portal to view logs (System.Diagnostics.Debug.WriteLine).