Skip to content

Commit a77dba7

Browse files
committed
Added Node article
1 parent cc5bae3 commit a77dba7

File tree

2 files changed

+206
-6
lines changed

2 files changed

+206
-6
lines changed

includes/iot-hub-howto-device-management-node.md

Lines changed: 203 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,218 @@ This section describes how to use device application code to:
2323
* Trigger a simulated device reboot
2424
* Use the reported properties to enable device twin queries to identify devices and when they were last rebooted
2525

26-
### Connect to a device
26+
### Install SDK packages
27+
28+
The [azure-iot-device](/javascript/api/azure-iot-device) package contains objects that interface with IoT devices. Run this command to install the **azure-iot-device** device SDK on your development machine:
29+
30+
```cmd/sh
31+
npm install azure-iot-device --save
32+
```
33+
34+
### Choose a transport protocol
35+
36+
The `Client` object supports these protocols:
37+
38+
* `Amqp`
39+
* `Http` - When using `Http`, the `Client` instance checks for messages from IoT Hub infrequently (a minimum of every 25 minutes).
40+
* `Mqtt`
41+
* `MqttWs`
42+
* `AmqpWs`
43+
44+
Install needed transport protocols on your development machine.
45+
46+
For example, this command installs the `Amqp` protocol:
47+
48+
```cmd/sh
49+
npm install azure-iot-device-amqp --save
50+
```
51+
52+
For more information about the differences between MQTT, AMQP, and HTTPS support, see [Cloud-to-device communications guidance](../articles/iot-hub/iot-hub-devguide-c2d-guidance.md) and [Choose a communication protocol](../articles/iot-hub/iot-hub-devguide-protocols.md).
53+
54+
### Create a client object
55+
56+
Create a `Client` object using the installed package.
57+
58+
For example:
59+
60+
```javascript
61+
const Client = require('azure-iot-device').Client;
62+
```
63+
64+
### Create a protocol object
65+
66+
Create a `Protocol` object using an installed transport package.
67+
68+
This example assigns the AMQP protocol:
69+
70+
```javascript
71+
const Protocol = require('azure-iot-device-amqp').Amqp;
72+
```
73+
74+
### Add the device connection string and transport protocol
75+
76+
Call [fromConnectionString](/javascript/api/azure-iot-device/client?#azure-iot-device-client-fromconnectionstring) to supply device connection parameters:
77+
78+
* **connStr** - The device connection string.
79+
* **transportCtor** - The transport protocol.
80+
81+
This example uses the `Amqp` transport protocol:
82+
83+
```javascript
84+
const deviceConnectionString = "{IoT hub device connection string}"
85+
const Protocol = require('azure-iot-device-mqtt').Amqp;
86+
let client = Client.fromConnectionString(deviceConnectionString, Protocol);
87+
```
88+
89+
### Open the connection to IoT Hub
90+
91+
Use the [open](/javascript/api/azure-iot-device/client?#azure-iot-device-client-open) method to open connection between an IoT device and IoT Hub.
92+
93+
For example:
94+
95+
```javascript
96+
client.open(function(err) {
97+
if (err) {
98+
console.error('error connecting to hub: ' + err);
99+
process.exit(1);
100+
}
101+
})
102+
```
27103

28104
### Create a direct method callback
29105

106+
Call [onDeviceMethod](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient?#azure-iot-device-iothubdeviceclient-on-method-request-received) to create a handler function or coroutine that is called when a direct method is received. The listener is associated with a method name keyword, such as "reboot". The method name can be used in an IoT Hub or backend application to trigger the callback method on the device.
107+
108+
This example sets up a direct method handler named `onReboot`.
109+
110+
```javascript
111+
client.onDeviceMethod('reboot', onReboot);
112+
```
113+
114+
In this example, the `onReboot` callback method implements the direct method on the device. The code is executed when the "rebootDevice" direct method is called from a service application. This code updates reported properties related to a simulated device reboot. The reported properties can be read and verified by an IoT Hub or backend application, as demonstrated in the **Create a backend application** section of this article.
115+
116+
```javascript
117+
var onReboot = function(request, response) {
118+
119+
// Respond the cloud app for the direct method
120+
response.send(200, 'Reboot started', function(err) {
121+
if (err) {
122+
console.error('An error occurred when sending a method response:\n' + err.toString());
123+
} else {
124+
console.log('Response to method \'' + request.methodName + '\' sent successfully.');
125+
}
126+
});
127+
128+
// Report the reboot before the physical restart
129+
var date = new Date();
130+
var patch = {
131+
iothubDM : {
132+
reboot : {
133+
lastReboot : date.toISOString(),
134+
}
135+
}
136+
};
137+
138+
// Get device Twin
139+
client.getTwin(function(err, twin) {
140+
if (err) {
141+
console.error('could not get twin');
142+
} else {
143+
console.log('twin acquired');
144+
twin.properties.reported.update(patch, function(err) {
145+
if (err) throw err;
146+
console.log('Device reboot twin state reported')
147+
});
148+
}
149+
});
150+
151+
// Add your device's reboot API for physical restart.
152+
console.log('Rebooting!');
153+
};
154+
```
155+
30156
### SDK device samples
31157

158+
The Azure IoT SDK for Node.js provides working samples of device apps that handle device management tasks. For more information, see [The device management pattern samples](https://github.com/Azure/azure-iot-sdk-node/blob/a85e280350a12954f46672761b0b516d08d374b5/doc/dmpatterns.md).
159+
32160
## Create a backend application
33161

162+
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.
163+
164+
### Install service SDK package
165+
166+
Run this command to install **azure-iothub** on your development machine:
167+
168+
```cmd/sh
169+
npm install azure-iothub --save
170+
```
171+
172+
### Create a Registry object
173+
174+
The [Registry](/javascript/api/azure-iothub/registry) class exposes all methods required to interact with direct methods from a backend application.
175+
34176
### Connect to IoT hub
35177

178+
Use [fromConnectionString](/javascript/api/azure-iothub/registry?#azure-iothub-registry-fromconnectionstring) to connect to IoT hub.
179+
180+
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.
181+
182+
As a parameter to `CreateFromConnectionString`, supply the **service** shared access policy connection string. For more information about shared access policies, see [Control access to IoT Hub with shared access signatures](/azure/iot-hub/authenticate-authorize-sas).
183+
184+
```javascript
185+
var Registry = require('azure-iothub').Registry;
186+
var Client = require('azure-iothub').Client;
187+
var connectionString = '{IoT hub shared access policy connection string}';
188+
var client = Client.fromConnectionString(connectionString);
189+
var registry = Registry.fromConnectionString(serviceConnectionString);
190+
```
191+
36192
### Invoke a method on a device
37193

194+
Use [invokeDeviceMethod](/javascript/api/azure-iothub/client?view=azure-node-latest#azure-iothub-client-invokedevicemethod) to invoke a direct method by name on a device. The method name parameter identifies the direct method. The method name is "reboot" in the examples within this article.
195+
196+
```javascript
197+
var startRebootDevice = function(twin) {
198+
199+
var methodName = "reboot";
200+
201+
var methodParams = {
202+
methodName: methodName,
203+
payload: null,
204+
timeoutInSeconds: 30
205+
};
206+
207+
client.invokeDeviceMethod(deviceToReboot, methodParams, function(err, result) {
208+
if (err) {
209+
console.error("Direct method error: "+err.message);
210+
} else {
211+
console.log("Successfully invoked the device to reboot.");
212+
}
213+
});
214+
};
215+
```
216+
217+
This example fuction uses device twin queries to discover the last reboot time for the device that was updated as described in the **Create a direct method callback** section of this article.
218+
219+
```javascript
220+
var queryTwinLastReboot = function() {
221+
222+
registry.getTwin(deviceToReboot, function(err, twin){
223+
224+
if (twin.properties.reported.iothubDM != null)
225+
{
226+
if (err) {
227+
console.error('Could not query twins: ' + err.constructor.name + ': ' + err.message);
228+
} else {
229+
var lastRebootTime = twin.properties.reported.iothubDM.reboot.lastReboot;
230+
console.log('Last reboot time: ' + JSON.stringify(lastRebootTime, null, 2));
231+
}
232+
} else
233+
console.log('Waiting for device to report last reboot time.');
234+
});
235+
};
236+
```
237+
38238
### SDK service samples
239+
240+
The Azure IoT SDK for Node.js provides working samples of service apps that handle device management tasks. For more information, see [The device management pattern samples](https://github.com/Azure/azure-iot-sdk-node/blob/a85e280350a12954f46672761b0b516d08d374b5/doc/dmpatterns.md).

includes/iot-hub-howto-device-management-python.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ This section describes how to use device application code to:
2727

2828
### Device import statements
2929

30-
Add import statements for `IoTHubDeviceClient`.
30+
Add import statements to access `IoTHubDeviceClient` and `MethodResponse`.
3131

3232
```python
3333
# import the device client library
@@ -53,7 +53,7 @@ device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)
5353

5454
Call [on_method_request_received](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient?#azure-iot-device-iothubdeviceclient-on-method-request-received) to create a handler function or coroutine that is called when a direct method is received. The listener is associated with a method name keyword, such as "reboot". The method name can be used in an IoT Hub or backend application to trigger the callback method on the device.
5555

56-
This example sets up a desired properties patch handler named `method_request_handler`.
56+
This example sets up a direct method handler named `method_request_handler`.
5757

5858
For example:
5959

@@ -66,9 +66,7 @@ except:
6666
client.shutdown()
6767
```
6868

69-
In this example, the `method_request_handler` callback method implements the direct method on the device. This code updates reported properties related to a simulated device reboot. The reported properties can be read and verified by an IoT Hub or backend application, as demonstrated in the **Create a backend application** section of this article.
70-
71-
This example sets up a callback listener named `method_request_handler` that triggers when the "rebootDevice" direct method is called from a service application.
69+
In this example, the `method_request_handler` callback method implements the direct method on the device. The code is executed when the "rebootDevice" direct method is called from a service application. This code updates reported properties related to a simulated device reboot. The reported properties can be read and verified by an IoT Hub or backend application, as demonstrated in the **Create a backend application** section of this article.
7270

7371
```python
7472
# Define the handler for method requests

0 commit comments

Comments
 (0)