For using Azure IoT Hub, you can utilize direct method.
For Windows IoT Core, you can start with UWP app.
The following is a simple sample of implementing the direct method on the device:
using Microsoft.Azure.Devices.Client;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
namespace App1
{
public sealed partial class MainPage : Page
{
private string connectionStr = "HostName=[YOUR HUB NAME].azure-devices.net;DeviceId=[YOUR DEVICE ID];SharedAccessKey=[SHARED ACCESS KEY]";
private DeviceClient deviceClient;
public MainPage()
{
this.InitializeComponent();
AddDirectMethod();
}
private async void AddDirectMethod()
{
deviceClient = DeviceClient.CreateFromConnectionString(connectionStr, TransportType.Mqtt);
await deviceClient.SetMethodHandlerAsync("TurnOn", new MethodCallback(TurnOnRelay), null);
await deviceClient.SetMethodHandlerAsync("TurnOff", new MethodCallback(TurnOffRelay), null);
}
private Task<MethodResponse> TurnOffRelay(MethodRequest methodRequest, object userContext)
{
Debug.WriteLine("Direct method name:" + methodRequest.Name);
// Put Relay toggle code here.
// ...
string result = "{\"Relay Status\":\"The Relay is OFF.\"}";
return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
}
private Task<MethodResponse> TurnOnRelay(MethodRequest methodRequest, object userContext)
{
Debug.WriteLine("Direct method name:" + methodRequest.Name);
// Put Relay toggle code here.
// ...
string result = "{\"Relay Status\":\"The Relay is ON.\"}";
return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
}
}
}
You need install NuGet package microsoft.azure.devices.client to your UWP app. Here is a detailed tutorial of a .NET console app you can reference.
You can call direct method from Azure Portal like this:
