-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
87 lines (74 loc) · 2.32 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
'use strict';
const suncalc = require('suncalc');
module.exports = homebridge => {
const Characteristic = homebridge.hap.Characteristic;
const Service = homebridge.hap.Service;
// Frequency of updates during transition periods.
const UPDATE_FREQUENCY = 1000;
class DaylightAccessory {
constructor(log, config) {
if (!config.location ||
!Number.isFinite(config.location.lat) ||
!Number.isFinite(config.location.lng)) {
throw new Error('Invalid or missing `location` configuration.');
}
this.location = config.location;
this.service = new Service.LightSensor(config.name);
this.updateAmbientLightLevel();
}
updateAmbientLightLevel() {
const nowDate = new Date();
const now = nowDate.getTime();
const sunDates = suncalc.getTimes(
nowDate,
this.location.lat,
this.location.lng
);
const times = {
sunrise: sunDates.sunrise.getTime(),
sunriseEnd: sunDates.sunriseEnd.getTime(),
sunsetStart: sunDates.sunsetStart.getTime(),
sunset: sunDates.sunset.getTime(),
};
let lightRatio;
let nextUpdate;
if (
now > times.sunrise &&
now < times.sunriseEnd
) {
lightRatio =
(now - times.sunrise) /
(times.sunriseEnd - times.sunrise);
nextUpdate = now + UPDATE_FREQUENCY;
} else if (
now > times.sunriseEnd &&
now < times.sunsetStart
) {
lightRatio = 1;
nextUpdate = times.sunsetStart;
} else if (
now > times.sunsetStart &&
now < times.sunset
) {
lightRatio =
(times.sunset - now) /
(times.sunset - times.sunsetStart);
nextUpdate = now + UPDATE_FREQUENCY;
} else {
lightRatio = 0;
nextUpdate = times.sunrise;
}
// Range (in lux) from 0.0001 to 100000 in increments of 0.0001.
const lightLevel = Math.round(1 + lightRatio * 999999999) / 10000;
this.service.setCharacteristic(
Characteristic.CurrentAmbientLightLevel,
lightLevel
);
setTimeout(this.updateAmbientLightLevel.bind(this), nextUpdate - now);
}
getServices() {
return [this.service];
}
}
homebridge.registerAccessory('homebridge-daylight', 'Daylight', DaylightAccessory);
};