forked from dansays/homebridge-applescript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
92 lines (68 loc) · 2.15 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
var Service;
var Characteristic;
var applescript = require('applescript');
module.exports = (homebridge) => {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory('homebridge-applescript-status', 'AppleScript', AppleScriptAccessory);
}
class AppleScriptAccessory {
constructor (log, config) {
this.log = log;
this.service = 'Switch';
this.config = config;
this.retrieveSwitchState = this.retrieveSwitchState.bind(this)
this.on = false
}
setState (on, callback) {
const state = on ? 'on' : 'off';
let command = this.config[state];
if (this.on === on) return callback()
const done = (err) => {
if (err) {
this.log('Error: ' + err);
callback(err || new Error('Error setting ' + this.config.name + ' to ' + state));
} else {
this.on = on
this.log('Set ' + this.config.name + ' to ' + state);
callback(null);
}
}
if (this.config.type === 'file') {
applescript.execFile(command, done);
} else {
command = command.replace(/''/g, '"');
applescript.execString(command, done);
}
}
retrieveSwitchState () {
let command = this.config.status;
if (!command) return
const done = (err, on) => {
setTimeout(this.retrieveSwitchState, (this.config.statusCheckInterval || 1) * 1000);
if (err) return;
this.on = !!on
this.switchService.setCharacteristic(Characteristic.On, !!on);
}
if (this.config.type === 'file') {
applescript.execFile(command, done);
} else {
command = command.replace(/''/g, '"');
applescript.execString(command, done);
}
}
getServices () {
const informationService = new Service.AccessoryInformation();
const switchService = new Service.Switch(this.config.name);
informationService
.setCharacteristic(Characteristic.Manufacturer, 'Applescript Manufacturer')
.setCharacteristic(Characteristic.Model, 'Applescript Model')
.setCharacteristic(Characteristic.SerialNumber, 'Applescript Serial Number');
switchService
.getCharacteristic(Characteristic.On)
.on('set', this.setState.bind(this));
this.switchService = switchService;
this.retrieveSwitchState();
return [switchService];
}
}