-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.js
More file actions
48 lines (37 loc) · 1.46 KB
/
app.js
File metadata and controls
48 lines (37 loc) · 1.46 KB
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
var mqtt = require('mqtt');
var CONFIG = require('./config.json');
// The port number is specified at
// https://developer.artik.cloud/documentation/connect-the-data/mqtt.html#key-concepts
var credentials = {
port: 8883,
username: CONFIG.DEVICE_ID,
password: CONFIG.DEVICE_TOKEN
}
// Per https://www.npmjs.com/package/mqtt#client, the URL can be on the following protocols:
// 'mqtt', 'mqtts', 'tcp', 'tls', 'ws', 'wss'
//
// For ARTIK Cloud, mqtt client must be SSL-capable.
// use ‘mqtts’, which has security layer on top of mqtt
var client = mqtt.connect('mqtts://api.artik.cloud', credentials);
// ARTIK Cloud only allows the following 2 paths on MQTT
var PUBLISH_MESSAGE_PATH = "/v1.1/messages/" + CONFIG.DEVICE_ID;
var SUBSCRIBE_ACTION_PATH = "/v1.1/actions/" + CONFIG.DEVICE_ID;
client.on('connect', function () {
console.log("Start MQTT session ...");
var sampleData = getSampleData();
console.log("publishing data:", sampleData);
console.log("publish path:", PUBLISH_MESSAGE_PATH);
client.publish(PUBLISH_MESSAGE_PATH, sampleData);
console.log("Use browser to see your data in realtime https://artik.cloud/my/data")
// Example for subscribing to receive Action
// client.subscribe(SUBSCRIBE_ACTION_PATH);
client.end()
console.log("End MQTT session ...");
})
function getSampleData() {
var tempVal = Math.floor((Math.random() * 200));
//fields key/value for you ARTIK Cloud device
return JSON.stringify({
"temp": tempVal
})
}