-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.js
executable file
·93 lines (80 loc) · 2.68 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
88
89
90
91
92
93
"use strict";
var Service, Characteristic, HomebridgeAPI;
var exec = require('child_process').exec;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
HomebridgeAPI = homebridge;
homebridge.registerAccessory("homebridge-cmdtrigger", "CmdTrigger", CmdTrigger);
}
function CmdTrigger(log, config) {
this.log = log;
this.name = config.name;
this.command = config.command ? config.command : "echo HelloWorld";
this.stateful = config.stateful;
this.delay = config.delay ? config.delay : 800;
this.debug = config.debug ? config.debug : false;
this.execAfterDelay = config.execAfterDelay
this._service = new Service.Switch(this.name);
this.cacheDirectory = HomebridgeAPI.user.persistPath();
this.storage = require('node-persist');
this.storage.initSync({dir:this.cacheDirectory, forgiveParseErrors: true});
this._service.getCharacteristic(Characteristic.On)
.on('set', this._setOn.bind(this));
if (this.stateful) {
var cachedState = this.storage.getItemSync(this.name);
if((cachedState === undefined) || (cachedState === false)) {
this._service.setCharacteristic(Characteristic.On, false);
} else {
this._service.setCharacteristic(Characteristic.On, true);
}
}
}
CmdTrigger.prototype.getServices = function() {
return [this._service];
}
CmdTrigger.prototype._setOn = function(on, callback) {
this.log("Setting '" + this.name + "' " + on);
if (on && !this.stateful) {
if (!this.execAfterDelay) {
//Execute command from config file and turn switch off again after configured delay
this.log("Executing command: '" + this.command + "'");
if(debug){
exec(this.command, (err, stdout, stderr) => {
if (err) {
this.log(err);
return;
}
this.log(stdout);
});
} else {
exec(this.command);
}
setTimeout(function() {
this._service.setCharacteristic(Characteristic.On, false);
}.bind(this), this.delay);
}
else{
//Execute command after configured delay and turn switch off again
setTimeout(function() {
this.log("Executing command: '" + this.command + "'");
if(debug){
exec(this.command, (err, stdout, stderr) => {
if (err) {
this.log(err);
return;
}
this.log(stdout);
});
} else {
exec(this.command);
}
this._service.setCharacteristic(Characteristic.On, false);
}.bind(this), this.delay);
}
}
if (this.stateful) {
this.storage.setItemSync(this.name, on);
}
callback();
}