-
Notifications
You must be signed in to change notification settings - Fork 0
/
svitch-manager.js
78 lines (68 loc) · 1.78 KB
/
svitch-manager.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
var spawn = require('child_process').spawn;
var util = require('util');
var SvitchManager = function () {
};
SvitchManager.prototype = {
getSvitches: function () {
return new Promise(function (resolve, reject) {
var proc = spawn('php', ['orvibo.php', 'list']);
var switches;
proc.stdout.on('data', function (data) {
if (data.toString().trim().length) {
svitches = JSON.parse(data);
// Convert to array
svitches = Object.keys(svitches).map(function (key) {
var svitch = svitches[key];
svitch.id = key;
return svitch;
});
resolve(svitches);
}
});
proc.stderr.on('data', function (data) {
reject(data);
});
proc.on('close', function (code) {
console.log('child process exited with code ' + code);
});
});
},
getById: function (id) {
return this.getSvitches()
.then(function (svitches) {
return new Promise(function (resolve, reject) {
var svitch = svitches.filter(function (svitch) {
return svitch.id === id;
})[0];
if (svitch) {
resolve(svitch);
} else {
reject(util.format('No switch with id %s exists', id));
}
});
});
},
/**
* Turns a svitch on or off
* @param {String} id svitch id
* @param {Number} state On (1) or off (0)
* @return {Promise}
*/
setSvitchState: function (id, state) {
return new Promise(function (resolve, reject) {
var proc = spawn('php', ['orvibo.php', state === 1 ? 'on' : 'off', id]);
var switches;
proc.stdout.on('data', function (data) {
resolve(data);
});
proc.stderr.on('data', function (data) {
reject(data);
});
proc.on('close', function (code) {
console.log('toggle process exited with code ' + code);
});
});
}
};
// Export singleton
module.exports = new SvitchManager();