forked from Azure/azure-iot-sdk-node
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdevice_methods.js
82 lines (66 loc) · 2.4 KB
/
device_methods.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
'use strict';
require('es5-shim');
var Protocol = require('azure-iot-device-mqtt').Mqtt;
var Client = require('azure-iot-device').Client;
var client = null;
function main() {
// receive the IoT Hub connection string as a command line parameter
if(process.argv.length < 3) {
console.error('Usage: node device_methods.js <<IoT Hub Device Connection String>>');
process.exit(1);
}
// open a connection to the device
var deviceConnectionString = process.argv[2];
client = Client.fromConnectionString(deviceConnectionString, Protocol);
client.open(onConnect);
}
function onConnect(err) {
if(!!err) {
console.error('Could not connect: ' + err.message);
} else {
console.log('Connected to device. Registering handlers for methods.');
// register handlers for all the method names we are interested in
client.onDeviceMethod('getDeviceLog', onGetDeviceLog);
client.onDeviceMethod('lockDoor', onLockDoor);
}
}
function onGetDeviceLog(request, response) {
printDeviceMethodRequest(request);
// Implement actual logic here.
// complete the response
response.send(200, 'example payload', function(err) {
if(!!err) {
console.error('An error ocurred when sending a method response:\n' +
err.toString());
} else {
console.log('Response to method \'' + request.methodName +
'\' sent successfully.' );
}
});
}
function onLockDoor(request, response) {
printDeviceMethodRequest(request);
// Implement actual logic here.
// complete the response
response.send(200, function(err) {
if(!!err) {
console.error('An error ocurred when sending a method response:\n' +
err.toString());
} else {
console.log('Response to method \'' + request.methodName +
'\' sent successfully.' );
}
});
}
function printDeviceMethodRequest(request) {
// print method name
console.log('Received method call for method \'' + request.methodName + '\'');
// if there's a payload just do a default console log on it
if(!!(request.payload)) {
console.log('Payload:\n' + request.payload);
}
}
// get the app rolling
main();