This repository has been archived by the owner on Oct 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 73
/
SimulatedDevice-2.js
72 lines (58 loc) · 2.21 KB
/
SimulatedDevice-2.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
'use strict';
// A test SAS token. To generate using the CLI:
// az iot hub generate-sas-token --device-id MyTestDevice --hub-name {YourIoTHubName}
var test_token = '{your test token}'
// Using the Node.js Device SDK for IoT Hub:
// https://github.com/Azure/azure-iot-sdk-node
// The sample connects to a device-specific MQTT endpoint on your IoT Hub.
var Protocol = require('azure-iot-device-mqtt').Mqtt;
var Client = require('azure-iot-device').Client;
var Message = require('azure-iot-device').Message;
var NoRetry = require('azure-iot-common').NoRetry;
var crypto = require('crypto');
// Example code showing how to generate a SAS token.
var generateSasToken = function(resourceUri, signingKey, policyName, expiresInMins) {
resourceUri = encodeURIComponent(resourceUri);
// Set expiration in seconds
var expires = (Date.now() / 1000) + expiresInMins * 60;
expires = Math.ceil(expires);
var toSign = resourceUri + '\n' + expires;
// Use crypto
var hmac = crypto.createHmac('sha256', new Buffer(signingKey, 'base64'));
hmac.update(toSign);
var base64UriEncoded = encodeURIComponent(hmac.digest('base64'));
// Construct autorization string
var token = "SharedAccessSignature sr=" + resourceUri + "&sig="
+ base64UriEncoded + "&se=" + expires;
if (policyName) token += "&skn="+policyName;
return token;
};
// There are two ways to create a SAS token for a device to connect:
//
// var token = generateSasToken(
// 'hubname.azure-devices.net/devices/devicename',
// 'device shared access policy key',
// 'device',
// expiryInMins)
//
// var token = generateSasToken(
// 'hubname.azure-devices.net/devices/devicename',
// 'device key',
// null,
// expiryInMins)
var client = Client.fromSharedAccessSignature(test_token, Protocol);
console.log('IoT Hub troubleshooting tutorial\nSimulated device #2\n')
// Disable retries so you see the connection error immediately
client.setRetryPolicy(new NoRetry());
// Callback function to run after connecting to the IoT hub.
var connectCallback = function (err) {
if (err) {
console.log('Could not connect: ' + err);
} else {
console.log('Client connected');
}
client.close();
process.exit(0);
};
// Connect to the IoT hub.
client.open(connectCallback);