diff --git a/src/fluxAccessory.ts b/src/fluxAccessory.ts index a13057d..899e904 100644 --- a/src/fluxAccessory.ts +++ b/src/fluxAccessory.ts @@ -10,6 +10,8 @@ import HueError = require("node-hue-api/lib/HueError"); let Service: HAPNodeJS.Service; let Characteristic: HAPNodeJS.Characteristic; +const SECONDS_IN_DAY = 86400000; +const SECONDS_IN_HOUR = 3600; export interface IFluxProps { api: any; @@ -198,8 +200,9 @@ export class FluxAccessory implements IAccessory { } const now = new Date(Date.now()); - const sunset = this._times.sunset; - const sunrise = new Date(this._times.sunrise.setTime(this._times.sunrise.getTime() + 1 * 86400000)); + //Pad start time by an hour before sunset + const start = new Date(this._times.sunset.getTime() - 3 * 1000 * SECONDS_IN_HOUR); + const end = new Date(this._times.sunrise.getTime() + 1 * SECONDS_IN_DAY); // const sunset = new Date('Wed, 15 Apr 2020 21:00:00 GMT'); // const sunrise = new Date('Wed, 15 Apr 2020 23:00:00 GMT'); @@ -209,22 +212,22 @@ export class FluxAccessory implements IAccessory { let percentageComplete = 0; let newTemp = 0; - const midTime = (sunrise.getTime() - sunset.getTime()) / 2; - const mid = new Date(new Date().setTime(sunset.getTime() + midTime)); + const midTime = (end.getTime() - start.getTime()) / 2; + const mid = new Date(new Date().setTime(start.getTime() + midTime)); const tempRange = Math.abs(startColorTemp - stopColorTemp); - if ((sunset < now) && (now < mid)) { + if ((start < now) && (now < mid)) { //Before sunset; calculate temp based on TOD - const totalDecreaseTime = (mid.getTime() - sunset.getTime()) / 1000; - const secondsFromStart = (now.getTime() - sunset.getTime()) / 1000; + const totalDecreaseTime = (mid.getTime() - start.getTime()) / 1000; + const secondsFromStart = (now.getTime() - start.getTime()) / 1000; percentageComplete = secondsFromStart / totalDecreaseTime; const tempOffset = tempRange * percentageComplete; newTemp = startColorTemp - tempOffset; - } else if ((mid < now) && (now < sunrise)) { + } else if ((mid < now) && (now < end)) { //After sunset; calculate temp based on TOD - const totalIncreaseTime = (sunrise.getTime() - mid.getTime()) / 1000; - const secondsUntilSunrise = (sunrise.getTime() - now.getTime()) / 1000; + const totalIncreaseTime = (end.getTime() - mid.getTime()) / 1000; + const secondsUntilSunrise = (end.getTime() - now.getTime()) / 1000; percentageComplete = secondsUntilSunrise / totalIncreaseTime; const tempOffset = tempRange * percentageComplete;