forked from cr3ative/homebridge-shell-switch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
103 lines (88 loc) · 2.82 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
94
95
96
97
98
99
100
101
102
103
let Service;
let Characteristic;
let HomebridgeAPI;
const { exec } = require('child_process');
class ShellSwitch {
constructor(log, config) {
this.log = log;
// Setup Configuration
this.setupConfig(config);
// Persistent Storage
this.cacheDirectory = HomebridgeAPI.user.persistPath();
this.storage = require('node-persist');
this.storage.initSync({ dir: this.cacheDirectory, forgiveParseErrors: true });
// Setup Services
this.createSwitchService();
this.createAccessoryInformationService();
}
setupConfig(config) {
this.name = config.name;
this.onCmd = config.onCmd;
this.offCmd = config.offCmd;
this.stateful = config.stateful ? config.stateful : true;
}
getCachedState() {
const cachedState = this.storage.getItemSync(this.name);
if ((cachedState === undefined || cachedState === false)&&!this.stateless) {
return false;
}
return true;
}
createSwitchService() {
this.switchService = new Service.Switch(this.name);
this.switchService
.getCharacteristic(Characteristic.On)
.on('get', this.getSwitchState.bind(this))
.on('set', this.setSwitchState.bind(this));
this.restoringStateOnBoot = true;
const state = this.getCachedState();
this.switchService.setCharacteristic(Characteristic.On, state);
}
createAccessoryInformationService() {
this.accessoryInformationService = new Service.AccessoryInformation()
.setCharacteristic(Characteristic.Name, this.name)
.setCharacteristic(Characteristic.Manufacturer, 'Shell Command Switch')
.setCharacteristic(Characteristic.Model, 'Shell Command Switch');
}
getServices() {
return [this.accessoryInformationService, this.switchService];
}
getSwitchState(callback) {
const state = this.getCachedState();
callback(null, state);
}
setSwitchState(on, callback) {
// Don't actually toggle the switch state if we're just ensuring the
// existing state is being restored on boot.
if (this.restoringStateOnBoot) {
this.restoringStateOnBoot = false;
return callback();
}
let cmd = this.offCmd;
if (on) {
cmd = this.onCmd;
}
this.log(`Executing command: '${cmd}'`);
return exec(cmd, (error) => {
if (error) {
this.log(error);
} else {
if (this.stateful) {
this.log(`Setting switch to ${on}`);
this.storage.setItemSync(this.name, on);
}
else {
this.log(`Stateless switch set to ${on}`);
this.storage.setItemSync(this.name, on);
}
}
callback(error);
});
}
}
module.exports = (homebridge) => {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
HomebridgeAPI = homebridge;
homebridge.registerAccessory('homebridge-shell-switch', 'ShellSwitch', ShellSwitch);
};