/
index.js
65 lines (52 loc) · 1.56 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
const osascript = require('node-osascript');
let Service;
let Characteristic;
module.exports = homebridge => {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory('homebridge-app-switch', 'AppSwitch', AppSwitch);
};
function AppSwitch(log, config) {
const name = config.name;
const debug = config.debug;
this.appName = config.appName;
if (!config.appName) {
log('Missing appName in config!');
return;
}
this.log = function () {
if (!debug) {
return;
}
log.apply({}, Array.prototype.slice.call(arguments, 0));
};
log('Creating switch');
this.lightService = new Service.Switch(name);
log('Adding ON characteristic');
this.lightService
.getCharacteristic(Characteristic.On)
.on('set', this.setPowerState.bind(this))
.on('get', this.getPowerState.bind(this));
}
AppSwitch.prototype.getServices = function () {
return [this.lightService];
};
AppSwitch.prototype.setPowerState = function (powerState, callback) {
this.log('SET POWERSTATE - ' + powerState);
osascript.execute(`tell application "${this.appName}" to ${powerState ? 'activate' : 'quit'}`);
callback();
};
AppSwitch.prototype.getPowerState = function (callback) {
const log = this.log;
log('GET POWERSTATE');
osascript.execute(`tell application "System Events" to exists (processes where name is "${this.appName}")`, (err, res) => {
if (err) {
log('GET POWERSTATE - ERR - ' + err);
callback(err, null);
} else {
const state = res;
log('GET POWERSTATE SUCCESS - ' + state);
callback(null, state);
}
});
};