|
| 1 | +--- |
| 2 | +title: Device management using direct methods (.NET) |
| 3 | +titleSuffix: Azure IoT Hub |
| 4 | +description: How to use Azure IoT Hub direct methods with the Azure IoT SDK for .NET for device management tasks including invoking a remote device reboot. |
| 5 | +author: kgremban |
| 6 | +ms.author: kgremban |
| 7 | +ms.service: iot-hub |
| 8 | +ms.devlang: csharp |
| 9 | +ms.topic: include |
| 10 | +ms.date: 10/09/2024 |
| 11 | +ms.custom: mqtt, devx-track-csharp, devx-track-dotnet |
| 12 | +--- |
| 13 | + |
| 14 | +## Overview |
| 15 | + |
| 16 | +This article describes how to use the [Azure IoT SDK for .NET](https://github.com/Azure/azure-iot-sdk-csharp) to create device and backend service application code for device direct messages. |
| 17 | + |
| 18 | +## Create a device application |
| 19 | + |
| 20 | +This section describes how to use device application code to: |
| 21 | + |
| 22 | +* Respond to a direct method called by the cloud |
| 23 | +* Trigger a simulated device reboot |
| 24 | +* Use the reported properties to enable device twin queries to identify devices and when they were last rebooted |
| 25 | + |
| 26 | +[!INCLUDE [iot-authentication-device-connection-string.md](../../includes/iot-authentication-device-connection-string.md)] |
| 27 | + |
| 28 | +### Required device NuGet package |
| 29 | + |
| 30 | +Device client applications written in C# require the **Microsoft.Azure.Devices.Client** NuGet package. |
| 31 | + |
| 32 | +### Connect to a device |
| 33 | + |
| 34 | +The [DeviceClient](/dotnet/api/microsoft.azure.devices.client.deviceclient) class exposes all the methods required to interact with device messages from the device. |
| 35 | + |
| 36 | +Connect to the device using the [CreateFromConnectionString](/dotnet/api/microsoft.azure.devices.client.deviceclient.createfromconnectionstring?#microsoft-azure-devices-client-deviceclient-createfromconnectionstring(system-string-microsoft-azure-devices-client-transporttype)) method along with device connection string and the connection transport protocol. |
| 37 | + |
| 38 | +The `CreateFromConnectionString` [TransportType](/dotnet/api/microsoft.azure.devices.client.transporttype) transport protocol parameter supports the following transport protocols: |
| 39 | + |
| 40 | +* `Mqtt` |
| 41 | +* `Mqtt_WebSocket_Only` |
| 42 | +* `Mqtt_Tcp_Only` |
| 43 | +* `Amqp` |
| 44 | +* `Amqp_WebSocket_Only` |
| 45 | +* `Amqp_Tcp_Only` |
| 46 | + |
| 47 | +The `Http1` protocol is not supported for device twin updates. |
| 48 | + |
| 49 | +This example connects to a device using the `Mqtt` transport protocol. |
| 50 | + |
| 51 | +```csharp |
| 52 | +using Microsoft.Azure.Devices.Client; |
| 53 | +using Microsoft.Azure.Devices.Shared; |
| 54 | +using Newtonsoft.Json; |
| 55 | + |
| 56 | +static string DeviceConnectionString = "{IoT hub device connection string}"; |
| 57 | +static deviceClient = null; |
| 58 | +deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString, |
| 59 | + TransportType.Mqtt); |
| 60 | +``` |
| 61 | + |
| 62 | +### Create a direct method callback |
| 63 | + |
| 64 | +Use [SetMethodHandlerAsync](/dotnet/api/microsoft.azure.devices.client.deviceclient.setmethodhandlerasync) to initialize a callback listener method. |
| 65 | + |
| 66 | +This example sets up a callback listener named `onReboot`. |
| 67 | + |
| 68 | +```csharp |
| 69 | +try |
| 70 | +{ |
| 71 | + // setup callback for "reboot" method |
| 72 | + deviceClient.SetMethodHandlerAsync("reboot", onReboot, null).Wait(); |
| 73 | + Console.WriteLine("Waiting for reboot method\n Press enter to exit."); |
| 74 | + Console.ReadLine(); |
| 75 | + |
| 76 | + Console.WriteLine("Exiting..."); |
| 77 | + |
| 78 | + // as a good practice, remove the "reboot" handler |
| 79 | + deviceClient.SetMethodHandlerAsync("reboot", null, null).Wait(); |
| 80 | + deviceClient.CloseAsync().Wait(); |
| 81 | +} |
| 82 | +catch (Exception ex) |
| 83 | +{ |
| 84 | + Console.WriteLine(); |
| 85 | + Console.WriteLine("Error in sample: {0}", ex.Message); |
| 86 | +} |
| 87 | +``` |
| 88 | + |
| 89 | +In this example, the `onReboot` callback method implements the direct method on the device: |
| 90 | + |
| 91 | +```csharp |
| 92 | +static Task<MethodResponse> onReboot(MethodRequest methodRequest, object userContext) |
| 93 | +{ |
| 94 | + // In a production device, you would trigger a reboot |
| 95 | + // scheduled to start after this method returns. |
| 96 | + // For this sample, we simulate the reboot by writing to the console |
| 97 | + // and updating the reported properties. |
| 98 | + try |
| 99 | + { |
| 100 | + Console.WriteLine("Rebooting!"); |
| 101 | + |
| 102 | + // Update device twin with reboot time. |
| 103 | + TwinCollection reportedProperties, reboot, lastReboot; |
| 104 | + lastReboot = new TwinCollection(); |
| 105 | + reboot = new TwinCollection(); |
| 106 | + reportedProperties = new TwinCollection(); |
| 107 | + lastReboot["lastReboot"] = DateTime.Now; |
| 108 | + reboot["reboot"] = lastReboot; |
| 109 | + reportedProperties["iothubDM"] = reboot; |
| 110 | + Client.UpdateReportedPropertiesAsync(reportedProperties).Wait(); |
| 111 | + } |
| 112 | + catch (Exception ex) |
| 113 | + { |
| 114 | + Console.WriteLine(); |
| 115 | + Console.WriteLine("Error in sample: {0}", ex.Message); |
| 116 | + } |
| 117 | + |
| 118 | + string result = @"{""result"":""Reboot started.""}"; |
| 119 | + return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200)); |
| 120 | +} |
| 121 | +``` |
| 122 | + |
| 123 | +> [!NOTE] |
| 124 | +> To keep things simple, this article does not implement any retry policy. In production code, you should implement retry policies (such as an exponential backoff), as suggested in [Transient fault handling](/azure/architecture/best-practices/transient-faults). |
| 125 | +
|
| 126 | +### SDK device samples |
| 127 | + |
| 128 | +The Azure IoT SDK for .NET provides working samples of device apps that handle device message tasks. For more information, see: |
| 129 | + |
| 130 | +* [Method Sample](https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples/getting%20started/MethodSample) |
| 131 | +* [Simulated Device with Command](https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples/getting%20started/SimulatedDeviceWithCommand) |
| 132 | +* [Temperature Controller](https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples/solutions/PnpDeviceSamples/TemperatureController) |
| 133 | +* [Thermostat Sample](https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples/solutions/PnpDeviceSamples/Thermostat) |
| 134 | + |
| 135 | +## Get the IoT hub connection string |
| 136 | + |
| 137 | +[!INCLUDE [iot-hub-howto-device-management-shared-access-policy-text](../../includes/iot-hub-howto-device-management-shared-access-policy-text.md)] |
| 138 | + |
| 139 | +## Create a backend application |
| 140 | + |
| 141 | +This section describes how to initiate a remote reboot on a device using a direct method. The app uses device twin queries to discover the last reboot time for that device. |
| 142 | + |
| 143 | +The [ServiceManager](/dotnet/api/microsoft.azure.devices.serviceclient) class exposes all methods required to create a backend application to send messages to devices. |
| 144 | + |
| 145 | +### Required service NuGet package |
| 146 | + |
| 147 | +Backend service applications require the **Microsoft.Azure.Devices** NuGet package. |
| 148 | + |
| 149 | +### Using statements |
| 150 | + |
| 151 | +Add the following `using` statements. |
| 152 | + |
| 153 | + ```csharp |
| 154 | + using Microsoft.Azure.Devices; |
| 155 | + using Microsoft.Azure.Devices.Shared; |
| 156 | + ``` |
| 157 | + |
| 158 | +### Connect to IoT hub |
| 159 | + |
| 160 | +Connect a backend application to a device using [CreateFromConnectionString](/dotnet/api/microsoft.azure.devices.serviceclient.createfromconnectionstring?#microsoft-azure-devices-serviceclient-createfromconnectionstring(system-string-microsoft-azure-devices-serviceclientoptions)). |
| 161 | + |
| 162 | +To invoke a direct method on a device through IoT Hub, your service needs the **service connect** permission. By default, every IoT Hub is created with a shared access policy named **service** that grants this permission. |
| 163 | + |
| 164 | +As a parameter to `CreateFromConnectionString`, supply the **service** shared access policy. For more information about shared access policies, see [Control access to IoT Hub with shared access signatures](/azure/iot-hub/authenticate-authorize-sas). |
| 165 | + |
| 166 | +[!INCLUDE [iot-authentication-service-connection-string.md](../../includes/iot-authentication-service-connection-string.md)] |
| 167 | + |
| 168 | +```csharp |
| 169 | +using Microsoft.Azure.Devices; |
| 170 | +static ServiceClient client; |
| 171 | +static string connectionString = "{IoT hub service shared access policy connection string}"; |
| 172 | +client = ServiceClient.CreateFromConnectionString(connectionString); |
| 173 | +``` |
| 174 | + |
| 175 | +### Invoke a method on a device |
| 176 | + |
| 177 | +To invoke a method on a device: |
| 178 | + |
| 179 | +1. Create a [CloudToDeviceMethod](/dotnet/api/microsoft.azure.devices.cloudtodevicemethod) object. Pass the device direct method name as a parameter. |
| 180 | +1. Call [InvokeDeviceMethodAsync](/dotnet/api/microsoft.azure.devices.serviceclient.invokedevicemethodasync?#microsoft-azure-devices-serviceclient-invokedevicemethodasync(system-string-microsoft-azure-devices-cloudtodevicemethod-system-threading-cancellationtoken)) to invoke the method on the device. |
| 181 | + |
| 182 | +This example calls the "reboot" method to initiate a reboot on the device. The "reboot" method is mapped to a listener on the device as described in the **Create a direct method callback** section above. |
| 183 | + |
| 184 | +```csharp |
| 185 | +CloudToDeviceMethod method = new CloudToDeviceMethod("reboot"); |
| 186 | +method.ResponseTimeout = TimeSpan.FromSeconds(30); |
| 187 | + |
| 188 | +CloudToDeviceMethodResult result = await |
| 189 | + |
| 190 | +static string targetDevice = "myDeviceId"; |
| 191 | +client.InvokeDeviceMethodAsync(targetDevice, method); |
| 192 | + |
| 193 | +Console.WriteLine("Invoked firmware update on device."); |
| 194 | +``` |
| 195 | + |
| 196 | +This example gets the device twin for the rebooting device and outputs the reported properties. This output shows that the `onReboot` method callback has updated the `lastReboot`, `Reboot`, and `iothubDM` reported properties. |
| 197 | + |
| 198 | +```csharp |
| 199 | +public static async Task QueryTwinRebootReported() |
| 200 | +{ |
| 201 | + Twin twin = await registryManager.GetTwinAsync(targetDevice); |
| 202 | + Console.WriteLine(twin.Properties.Reported.ToJson()); |
| 203 | +} |
| 204 | +``` |
| 205 | + |
| 206 | +### SDK service samples |
| 207 | + |
| 208 | +The Azure IoT SDK for .NET provides working samples of service apps that handle message tasks. For more information, see: |
| 209 | + |
| 210 | +* [Invoke Device Method](https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/service/samples/getting%20started/InvokeDeviceMethod) |
| 211 | +* [Method E2E Tests](https://github.com/Azure/azure-iot-sdk-csharp/tree/main/e2e/test/iothub/method) |
| 212 | +* [Temperature Controller](https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples/solutions/PnpDeviceSamples/TemperatureController) |
| 213 | +* [Thermostat Sample](https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples/solutions/PnpDeviceSamples/Thermostat) |
0 commit comments