-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathiot.101.js
87 lines (75 loc) · 2.19 KB
/
iot.101.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
83
84
85
86
87
"use strict";
/**
* node-rest-client doc is at https://www.npmjs.com/package/node-rest-client
*
* You need an Adafruit-IO account (free).
* You can interact with the IoT server directly at https://io.adafruit.com/olivierld
*
* This code will push some data sensor, and read some feed(s).
* Also see the WebUI at demos/iot.one.html (can run in standalone, just load it in a browser).
* From the WebUI you can change the state of the switch.
*
* Feeds keys we need here are:
* - onoff
*/
// Need the Adafruit-IO key as parameter
let key;
if (process.argv.length > 2) {
key = process.argv[2];
}
if (key === undefined) {
console.log("Usage: node " + __filename + " [Your-Adafruit-IO-Key]");
process.exit();
}
const ONOFF_FEED = "onoff";
const PREFIX = 'https://io.adafruit.com/api/feeds/';
let Client = require('node-rest-client').Client;
let client = new Client();
// Get data, through a callback
let getSwitchState = (cb) => {
let url = PREFIX + ONOFF_FEED;
let args = {
headers: {"X-AIO-Key": key}
};
client.get(url, args, (data, response) => {
// parsed response body as js object
// console.log("Last Value of [%s] (%s) was %s.", data.name, data.description, data.last_value);
// raw response
// console.log(response);
cb(data.last_value);
});
};
function setSwitchState(state) {
let args = {
data: { "value": state },
headers: { "Content-Type": "application/json",
"X-AIO-Key": key }
};
let url = PREFIX + ONOFF_FEED + "/data";
client.post(url, args, (data, response) => {
// parsed response body as js object
// console.log(data);
// raw response
console.log(response.headers.status);
});
};
let previousState;
let manageState = (state) => {
if (state !== previousState) {
console.log("State is now:" + state);
// Do something with the hardware here
previousState = state;
}
};
let interv = setInterval(() => {
getSwitchState(manageState);
}, 1000);
setTimeout(() => {
// Read sensor, push data
setSwitchState('ON');
}, 5000);
let exit = () => {
console.log("\nBye now!");
process.exit();
};
process.on('SIGINT', exit); // Ctrl C