Skip to content

Commit aa32e46

Browse files
committed
Updated version of Device Management using Direct Methods
1 parent 7229e55 commit aa32e46

6 files changed

+359
-14
lines changed

articles/iot-hub/TOC.yml

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -302,21 +302,9 @@
302302
href: module-twins-node.md
303303
- name: Get started with device management
304304
items:
305-
- name: CLI
306-
displayName: device management, status updates, device maintenance windows
307-
href: device-management-cli.md
308-
- name: .NET
309-
displayName: device management, status updates, device maintenance windows
310-
href: device-management-dotnet.md
311-
- name: Python
312-
displayName: device management, status updates, device maintenance windows
313-
href: device-management-python.md
314-
- name: Node.js
315-
displayName: device management, status updates, device maintenance windows
316-
href: device-management-node.md
317-
- name: Java
305+
- name: New version
318306
displayName: device management, status updates, device maintenance windows
319-
href: device-management-java.md
307+
href: how-to-device-management.md
320308
- name: Schedule and broadcast jobs
321309
items:
322310
- name: CLI
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
---
2+
title: Device management using direct methods
3+
titleSuffix: Azure IoT Hub
4+
description: How to use Azure IoT Hub direct methods for device management tasks including invoking a remote device reboot.
5+
author: kgremban
6+
ms.author: kgremban
7+
manager: lizross
8+
ms.service: iot-hub
9+
ms.devlang: csharp
10+
ms.topic: how-to
11+
ms.date: 10/09/2024
12+
zone_pivot_groups: iot-hub-howto-c2d-1
13+
ms.custom: mqtt, devx-track-csharp, devx-track-dotnet
14+
---
15+
16+
# Get started with device management
17+
18+
Back-end apps can use Azure IoT Hub primitives, such as [device twins](iot-hub-devguide-device-twins.md) and [direct methods](iot-hub-devguide-direct-methods.md), to remotely start and monitor device management actions on devices. This article shows you how a back-end app and a device app can work together to initiate and monitor a remote device reboot using IoT Hub.
19+
20+
Use a direct method to initiate device management actions (such as reboot, factory reset, and firmware update) from a back-end app in the cloud. The device is responsible for:
21+
22+
* Handling the method request sent from IoT Hub.
23+
24+
* Initiating the corresponding device-specific action on the device.
25+
26+
* Providing status updates through *reported properties* to IoT Hub.
27+
28+
You can use a back-end app in the cloud to run device twin queries to report on the progress of your device management actions.
29+
30+
This article shows you how to develop two types of applications:
31+
32+
* Device apps can call a direct method to reboot a device and report the last reboot time. Direct methods are invoked from the cloud.
33+
* Service apps can call a direct method in a device app through an IoT hub. The service app can display the response and updated reported properties.
34+
35+
[!INCLUDE [iot-hub-basic](../../includes/iot-hub-basic-whole.md)]
36+
37+
> [!NOTE]
38+
> This article is meant to complement [Azure IoT SDKs](iot-hub-devguide-sdks.md) samples that are referenced from within this article. You can use SDK tools to build both device and back-end applications.
39+
40+
## Prerequisites
41+
42+
* **An IoT hub**. Some SDK calls require the IoT Hub primary connection string, so make a note of the connection string.
43+
44+
* **A registered device**. Some SDK calls require the device primary connection string, so make a note of the connection string.
45+
46+
* **IoT Hub service connection string**
47+
48+
In this article, you create a back-end service that adds desired properties to a device twin and then queries the identity registry to find all devices with reported properties that have been updated accordingly. Your service needs the **service connect** permission to modify desired properties of a device twin, and it needs the **registry read** permission to query the identity registry. There is no default shared access policy that contains only these two permissions, so you need to create one.
49+
50+
To create a shared access policy that grants **service connect** and **registry read** permissions and get a connection string for this policy, follow these steps:
51+
52+
1. In the Azure portal, select **Resource groups**. Select the resource group where your hub is located, and then select your hub from the list of resources.
53+
54+
1. On the left-side pane of your hub, select **Shared access policies**.
55+
56+
1. From the top menu above the list of policies, select **Add shared policy access policy**.
57+
58+
1. In the **Add shared access policy** pane on the right, enter a descriptive name for your policy, such as "serviceAndRegistryRead". Under **Permissions**, select **Registry Read** and **Service Connect**, and then select **Add**.
59+
60+
1. Select your new policy from the list of policies.
61+
62+
1. Select the copy icon for the **Primary connection string** and save the value.
63+
64+
For more information about IoT Hub shared access policies and permissions, see [Control access to IoT Hub with shared access signatures](/azure/iot-hub/authenticate-authorize-sas).
65+
66+
* If your application uses the MQTT protocol, make sure that **port 8883** is open in your firewall. The MQTT protocol communicates over port 8883. This port may be blocked in some corporate and educational network environments. For more information and ways to work around this issue, see [Connecting to IoT Hub (MQTT)](../iot/iot-mqtt-connect-to-iot-hub.md#connecting-to-iot-hub).
67+
68+
* Language SDK requirements:
69+
* **.NET SDK** - Requires Visual Studio.
70+
* **Python SDK** - [Python version 3.7 or later](https://www.python.org/downloads/) is recommended. Make sure to use the 32-bit or 64-bit installation as required by your setup. When prompted during the installation, make sure to add Python to your platform-specific environment variable.
71+
* **Java** - Requires [Java SE Development Kit 8](/azure/developer/java/fundamentals/). Make sure you select **Java 8** under **Long-term support** to navigate to downloads for JDK 8.
72+
* **Node.js** - Requires Node.js version 10.0.x or later.
73+
74+
:::zone pivot="programming-language-csharp"
75+
76+
[!INCLUDE [iot-hub-howto-device-management-dotnet](../../includes/iot-hub-howto-device-management-dotnet.md)]
77+
78+
:::zone-end
79+
80+
:::zone pivot="programming-language-java"
81+
82+
[!INCLUDE [iot-hub-howto-device-management-java](../../includes/iot-hub-howto-device-management-java.md)]
83+
84+
:::zone-end
85+
86+
:::zone pivot="programming-language-python"
87+
88+
[!INCLUDE [iot-hub-howto-device-management-python](../../includes/iot-hub-howto-device-management-python.md)]
89+
90+
:::zone-end
91+
92+
:::zone pivot="programming-language-node"
93+
94+
[!INCLUDE [iot-hub-howto-device-management-node](../../includes/iot-hub-howto-device-management-node.md)]
95+
96+
:::zone-end
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
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)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
title: Device management using direct methods (Java)
3+
titleSuffix: Azure IoT Hub
4+
description: How to use Azure IoT Hub direct methods with the Azure IoT SDK for Java 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: amqp, mqtt, devx-track-java, devx-track-extended-java
12+
---
13+
14+
## Overview
15+
16+
This article describes how to use the [Azure IoT SDK for Java](https://github.com/Azure/azure-iot-sdk-java) to create device and backend service application code for device direct methods.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
title: Device management using direct methods (Node.js)
3+
titleSuffix: Azure IoT Hub
4+
description: How to use Azure IoT Hub direct methods with the Azure IoT SDK for Node.js 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-js
12+
---
13+
14+
## Overview
15+
16+
This article describes how to use the [Azure IoT SDK for Node.js](https://github.com/Azure/azure-iot-sdk-node) to create device and backend service application code for device direct methods.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
title: Device management using direct methods (Python)
3+
titleSuffix: Azure IoT Hub
4+
description: How to use Azure IoT Hub direct methods with the Azure IoT SDK for Python 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-python, py-fresh-zinc
12+
---
13+
14+
## Overview
15+
16+
This article describes how to use the [Azure IoT SDK for Python](https://github.com/Azure/azure-iot-sdk-python) to create device and backend service application code for device direct methods.

0 commit comments

Comments
 (0)