-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (66 loc) · 2.25 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
"use strict";
const { exec } = require("child_process");
const COMMANDDIR = '/var/lib/homebridge/CommandItSwitchExes';
var Service, Characteristic, HomebridgeAPI;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
HomebridgeAPI = homebridge;
homebridge.registerAccessory("homebridge-commanditswitch", "CommandItSwitch", CommandItSwitch);
}
function CommandItSwitch(log, config) {
this.log = log;
this.name = config.name;
this.exe = config.exe ? config.exe : "noop";
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.reverse) this._service.setCharacteristic(Characteristic.On, true);
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);
}
}
}
CommandItSwitch.prototype.getServices = function() {
return [this._service];
}
CommandItSwitch.prototype._setOn = function(on, callback) {
this.log("Setting switch to " + on);
if (on)
{
// Change the working directory...
console.log('Current Starting directory: ' + process.cwd());
if(process.cwd() != COMMANDDIR)
{
process.chdir(COMMANDDIR);
console.log('New directory: ' + process.cwd());
}
var ExecPath = this.exe;
//var ExecPath = './CommandItSwitchExes/' + this.exe;
this.log("Executing ('exe'): " + ExecPath);
exec(ExecPath, (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
this.log("Completed executing " + ExecPath);
setTimeout(function()
{
this._service.setCharacteristic(Characteristic.On, false);
}.bind(this), 1000);
}
callback();
}