forked from archanglmr/homebridge-occupancy-delay
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
381 lines (347 loc) · 11.3 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
"use strict";
var inherits = require("util").inherits;
var Service, Characteristic, HomebridgeAPI;
module.exports = function (homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
HomebridgeAPI = homebridge;
/**
* Characteristic "Time Remaining"
*/
Characteristic.TimeRemaining = function () {
Characteristic.call(
this,
"Time Remaining",
"1000006D-0000-1000-8000-0026BB765291"
);
this.setProps({
format: Characteristic.Formats.UINT64,
unit: Characteristic.Units.SECONDS,
maxValue: 3600,
minValue: 0,
minStep: 1,
perms: [
Characteristic.Perms.READ,
Characteristic.Perms.WRITE,
Characteristic.Perms.NOTIFY,
],
});
this.value = this.getDefaultValue();
};
inherits(Characteristic.TimeRemaining, Characteristic);
Characteristic.TimeRemaining.UUID = "1000006D-0000-1000-8000-0026BB765291";
/**
* Characteristic "Timeout Delay"
*/
Characteristic.TimeoutDelay = function () {
Characteristic.call(
this,
"Timeout Delay",
"1100006D-0000-1000-8000-0026BB765291"
);
this.setProps({
format: Characteristic.Formats.UINT64,
unit: Characteristic.Units.SECONDS,
maxValue: 3600,
minValue: 0,
minStep: 1,
perms: [
Characteristic.Perms.READ,
Characteristic.Perms.WRITE,
Characteristic.Perms.NOTIFY,
],
});
this.value = this.getDefaultValue();
};
inherits(Characteristic.TimeoutDelay, Characteristic);
Characteristic.TimeoutDelay.UUID = "1100006D-0000-1000-8000-0026BB765291";
/**
* Characteristic "Enabled", Bool attribute
*/
Characteristic.Enabled = function () {
Characteristic.call(this, "Enabled", Characteristic.Enabled.UUID);
this.setProps({
format: Characteristic.Formats.BOOL,
perms: [
Characteristic.Perms.READ,
Characteristic.Perms.NOTIFY,
Characteristic.Perms.WRITE,
],
});
};
inherits(Characteristic.Enabled, Characteristic);
Characteristic.Enabled.UUID = "79c5cb42-4554-11ea-b071-4bf76b071f47";
/**
* Service CustomSwitch, like switch but with an Enabled Characteristic
* so that can't accidentally be controlled through Siri, for instance
*/
Service.CustomSwitch = function (displayName, subtype) {
Service.call(this, displayName, Service.CustomSwitch.UUID, subtype);
this.addCharacteristic(Characteristic.Enabled);
};
inherits(Service.CustomSwitch, Service);
Service.CustomSwitch.UUID = "0ad4aebe-4555-11ea-bf4b-f30c92b99e11";
// Register
homebridge.registerAccessory(
"homebridge-occupancy-delay",
"OccupancyDelay",
OccupancyDelay
);
};
/**
* This accessory publishes an Occupancy Sensor as well as 1 or more slave
* Switches to control the status of the sensor. If any of the slaves are on
* then this sensor registers as "Occupancy Detected" ("Occupied). When all
* slaves are turned off this will remain "Occupied" for as long as the
* specified delay.
*
* Config:
*
* name: The name of this Occupancy Sensor and it's slave switches. If there are
* more than one slaves they will become "name 1", "name 2", etc.
* slaveCount (optional): Will create 1 slave Switch with the same name as the
* Occupancy Sensor by default. Change this if you need more than 1 Switch
* to control the sensor.
* delay: If set to less than 1 there will be no delay when all Switches are
* turned to off. Specify a number in seconds and the sensor will wait
* that long after all switches have been turned off to become
* "Un-occupied". If any slave Switch is turned on the counter will clear
* and start over once all Switches are off again.
*
*
* What can I do with this plugin?
* @todo: Addd use case and instructions here.
*/
class OccupancyDelay {
constructor(log, config) {
this.log = log;
this.name = config.name || "OccupancyDelay";
this.slaveCount = Math.max(1, config.slaveCount || 1);
this.delay = Math.min(3600, Math.max(0, parseInt(config.delay, 10) || 0));
this.stateful = config.stateful;
this.protect = !!config.protected;
this._timer = null;
this._timer_started = null;
this._timer_delay = 0;
this._interval = null;
this._interval_last_value = 0;
this._last_occupied_state = false;
this.switchServices = [];
this.occupancyService = new Service.OccupancySensor(this.name);
this.occupancyService.addCharacteristic(Characteristic.TimeoutDelay);
this.occupancyService.setCharacteristic(
Characteristic.TimeoutDelay,
this.delay
);
this.occupancyService
.getCharacteristic(Characteristic.TimeoutDelay)
.on("change", (event) => {
this.log("Setting delay to:", event.newValue);
this.delay = event.newValue;
});
this.occupancyService.addCharacteristic(Characteristic.TimeRemaining);
this.occupancyService.setCharacteristic(Characteristic.TimeRemaining, 0);
this.occupancyService
.getCharacteristic(Characteristic.TimeRemaining)
.on("change", (event) => {
if (event.newValue === 0 && event.oldValue > 0) {
this.log('Cancel timer and set occupancy to "NotDetected"');
this.setOccupancyNotDetected();
}
});
this.cacheDirectory = HomebridgeAPI.user.persistPath();
this.storage = require("node-persist");
this.storage.initSync({
dir: this.cacheDirectory,
forgiveParseErrors: true,
});
/* Make the slave Switches */
if (1 === this.slaveCount) {
this.log("Making a single slave switch");
this.switchServices.push(this._createSwitch());
} else {
this.log("Making " + this.slaveCount + " salve switches");
for (let i = 0, c = this.slaveCount; i < c; i += 1) {
this.switchServices.push(this._createSwitch(i + 1));
}
}
}
/**
* Starts the countdown timer.
*/
start() {
this.stop();
this._timer_started = new Date().getTime();
this.log("Timer started:", this.delay);
if (this.delay) {
this._timer = setTimeout(
this.setOccupancyNotDetected.bind(this),
this.delay * 1000
);
this._timer_delay = this.delay;
this._interval = setInterval(() => {
var elapsed = (new Date().getTime() - this._timer_started) / 1000,
newValue = Math.round(this._timer_delay - elapsed);
if (newValue !== this._interval_last_value) {
this.occupancyService.setCharacteristic(
Characteristic.TimeRemaining,
newValue
);
this._interval_last_value = newValue;
}
}, 250);
} else {
/* occupancy no longer detected */
this.setOccupancyNotDetected();
}
}
/**
* Stops the countdown timer
*/
stop() {
if (this._timer) {
this.log("Timer stopped");
clearTimeout(this._timer);
clearInterval(this._interval);
this._timer = null;
this._timer_started = null;
this._timer_delay = null;
this._interval = null;
}
}
setOccupancyDetected() {
this._last_occupied_state = true;
this.occupancyService.setCharacteristic(
Characteristic.OccupancyDetected,
Characteristic.OccupancyDetected.OCCUPANCY_DETECTED
);
if (this.delay) {
this.occupancyService.setCharacteristic(
Characteristic.TimeRemaining,
this.delay
);
}
}
setOccupancyNotDetected() {
this._last_occupied_state = false;
this.stop();
this.occupancyService.setCharacteristic(
Characteristic.OccupancyDetected,
Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED
);
if (this.delay) {
this.occupancyService.setCharacteristic(Characteristic.TimeRemaining, 0);
}
}
/**
* Checks all the slave Switches to see if any of them are on. If so this
* Occupancy Sensor will remain "Occupied". This is used as a callback when
* the "On" state changes on any of the slave Switches.
*/
checkOccupancy() {
this.log(`checking occupancy. Total: ${this.slaveCount}`);
var occupied = 0,
remaining = this.slaveCount,
/* callback for when all the switches values have been returend */
return_occupancy = (occupied) => {
if (occupied) {
if (this._last_occupied_state === !!occupied) {
this.stop();
} else {
this.setOccupancyDetected();
}
} else if (null === this._timer) {
this.start();
}
// @todo: Set a custom property for how many switches we're waiting for
this.log(
`checkOccupancy: ${occupied}. Last occupied state: ${this._last_occupied_state}`
);
},
/*
callback when we check a switches value. keeps track of the switches
returned value and decides when to finish the function
*/
set_value = (value) => {
this.log(`Remaining: ${remaining}, value: ${value}`);
remaining -= 1;
if (value) {
occupied += 1;
}
if (remaining === 0) {
return_occupancy(occupied);
}
};
/* look at all the slave switches "on" characteristic and return to callback */
const onCharacteristic = this.protect
? Characteristic.Enabled
: Characteristic.On;
for (let i = 0; i < this.slaveCount; i += 1) {
this.switchServices[i]
.getCharacteristic(onCharacteristic)
.getValue(function (err, value) {
if (!err) {
set_value(value);
}
});
// this.switchServices[i].setCharacteristic(Characteristic.On, true); // Looks like a bug
}
}
/**
* Homebridge function to return all the Services associated with this
* Accessory.
*
* @returns {*[]}
*/
getServices() {
var informationService = new Service.AccessoryInformation()
.setCharacteristic(Characteristic.Manufacturer, "github.com/archanglmr")
.setCharacteristic(Characteristic.Model, "1.0.2")
.setCharacteristic(Characteristic.SerialNumber, "20201006");
return [this.occupancyService, informationService, ...this.switchServices];
}
/**
* Internal helper function to create a new "Switch" that is ties to the
* status of this Occupancy Snesor.
*
* @param name
* @returns {Service.Switch|*}
* @private
*/
_createSwitch(name) {
var displayName = (name || "").toString(),
sw;
if (displayName.length) {
displayName = this.name + " " + displayName;
} else {
displayName = this.name;
}
this.log("Create Switch: " + displayName);
sw = new Service.Switch(displayName, name);
let statefulValue = false;
if (this.stateful) {
const cachedState = this.storage.getItemSync(this.name);
if (cachedState === undefined || cachedState === false) {
statefulValue = false;
} else {
statefulValue = true;
}
}
if (this.protect) {
sw = new Service.CustomSwitch(displayName, name);
sw.setCharacteristic(Characteristic.Enabled, statefulValue);
sw.getCharacteristic(Characteristic.Enabled).on(
"change",
this.checkOccupancy.bind(this)
);
} else {
sw = new Service.Switch(displayName, name);
sw.setCharacteristic(Characteristic.On, statefulValue);
sw.getCharacteristic(Characteristic.On).on(
"change",
this.checkOccupancy.bind(this)
);
}
return sw;
}
}