-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeviceless_mqtt.js
60 lines (47 loc) · 2 KB
/
deviceless_mqtt.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
// Assumptions:
// You have created a certificate in the AWS IoT console (or uploaded your own), and attached a policy with the necessary permissions
// (these would be iot:Connect, iot:Publish, and iot:Subscribe) on the appropriate resource(s) (arn:aws:iot:us-east-1:{accountId}:* is what I used; you can limit it further as appropriate)
//
// The certificate, private key, and CA for AWS IoT that you were told to download exist in ./certs/, with the names as specified in the keyPath, certPath, and caPath options below.
const AWS = require('aws-sdk');
const AWSDevices = require('aws-iot-device-sdk');
function init() {
return new Promise(function (resolve, reject) {
try {
const device = AWSDevices.device({
region: "us-east-1",
clientId: "use something meaningful here, uniquely identifying this connection - mqtt",
maximumReconnectTimeMs: 8000,
debug: false,
baseReconnectTimeMs: 500,
keyPath: __dirname + "/certs/private.key",
certPath: __dirname + "/certs/device.crt",
caPath: __dirname + "/certs/ca.pem"
})
}catch(ex) {
console.log(ex);
}
device.on('close', function() {
console.log('disconnected', arguments);
});
device.on('error', function() {
console.log('error', arguments);
});
device.on('reconnect', function() {
console.log('reconnecting', arguments);
});
device.on('timeout', function() {
console.log("Failed");
reject();
});
device.on('connect', function () {
console.log("Connected");
device.on('message', messageHandler);
device.subscribe("custom_topic", function() {resolve(device)})
});
});
};
function messageHandler(topic, message) {
console.log("message callback - topic: ", topic, "message:", message.toString())
}
init().then(device => device.publish("custom_topic", "test message"));