-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
88 lines (60 loc) · 1.91 KB
/
index.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";
var child_process = require('child_process')
, Service, Characteristic;
module.exports = function (homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-exec-switch", "ExecSwitch", ExecSwitch);
};
function ExecSwitch(log, config) {
var service;
if (!config.on) {
throw new Error("No `on` config key set.");
}
if (!config.off) {
throw new Error("No `off` config key set.");
}
if (!config.name) {
throw new Error("No `name` config key set.");
}
if (config.type) {
log("Configuring switch %s as %s.", config.name, config.type);
service = new Service[config.type](config.name);
}
else {
log("No switch type specified for %s, falling back to Switch.", config.name);
service = new Service.Switch(config.name);
}
this.getServices = function () {
return [service];
};
this._switch = function (newValue, callback) {
var command = newValue ? config.on : config.off;
log('Running set for %s -> %s', config.name, newValue);
this._exec(command, function (error) {
if (error) {
callback("Command `" + command + "` exited with code: " + error.code);
}
else {
callback();
}
});
};
this._status = function (callback) {
if (config.status) {
log('Running status command for %', config.name);
this._exec(config.status, function (error) {
callback(null, !!error);
});
}
else {
callback();
}
};
this._exec = child_process.exec;
service
.getCharacteristic(Characteristic.On)
.on('get', this._status.bind(this))
.on('set', this._switch.bind(this));
return this;
}