homebridge-virtual-accessories
Version:
Virtual HomeKit accessories for Homebridge.
114 lines • 3.62 kB
JavaScript
/* eslint-disable brace-style */
import { Utils } from './utils.js';
/**
* Timer
*/
export class Timer {
oneSecond = 1000; // in milliseconds
accessoryName;
log;
timerIsResettable = false;
id;
defaultDuration = 0;
updateIntervalMillis = this.oneSecond;
startTime;
isRunning = false;
runtime = 0;
remainingDurationMillis = 0;
logDebugCountdown = false;
constructor(accessoryName, log, timerIsResettable = false, duration) {
this.accessoryName = accessoryName;
this.log = log;
this.timerIsResettable = timerIsResettable;
this.startTime = Utils.now();
if (duration !== undefined) {
this.setDefaultDuration(duration);
}
}
start(callback, oneOffDuration, updateIntervalMillis) {
if (this.isRunning && !this.timerIsResettable) {
return;
}
// In case timer is running, stop it
this.stop();
// Now setup new run
this.runtime = (oneOffDuration === undefined) ? this.defaultDuration : oneOffDuration;
this.updateIntervalMillis = (updateIntervalMillis === undefined) ? this.oneSecond : updateIntervalMillis;
if (this.runtime > 0) {
this.remainingDurationMillis = this.runtime * 1000;
this.log.debug(`[${this.accessoryName} Timer] Start - Duration: ${this.runtime} seconds`);
this.id = setInterval(() => {
this.remainingDurationMillis -= this.updateIntervalMillis;
// We don't want this flooding the debug logs
if (this.logDebugCountdown && this.remainingDurationMillis % 1000 === 0) {
this.log.debug(`[${this.accessoryName} Timer] Remaining Duration: ${this.remainingDurationMillis} seconds`);
}
if (this.remainingDurationMillis <= 0) {
this.stop();
callback();
}
}, this.updateIntervalMillis);
this.startTime = Utils.now();
this.isRunning = true;
}
else {
callback();
}
}
stop() {
clearInterval(this.id);
this.isRunning = false;
this.runtime = 0;
this.remainingDurationMillis = 0;
this.updateIntervalMillis = this.oneSecond;
this.logDebugCountdown = false;
this.log.debug(`[${this.accessoryName} Timer] Stop - Cleared Duration: ${this.getRemainingDuration()} seconds`);
}
getStartTime() {
return this.startTime;
}
/**
* Returns runtime in seconds
*/
getRuntime() {
return this.runtime;
}
/**
* Returns interval in milliseconds
*/
getUpdateIntervalMillis() {
return this.updateIntervalMillis;
}
/**
* Returns duration in seconds
*/
getDefaultDuration() {
return this.defaultDuration;
}
/**
* Set duration in seconds
*/
setDefaultDuration(duration) {
this.defaultDuration = duration;
this.log.debug(`[${this.accessoryName} Timer] Set Duration: ${this.defaultDuration} seconds`);
}
/**
* Returns remaining duration in seconds
*/
getRemainingDuration() {
return Math.ceil(this.remainingDurationMillis / 1000);
}
/**
* Returns remaining duration in milliseconds
*/
getRemainingDurationMillis() {
return this.remainingDurationMillis;
}
isTimerRunning() {
return this.isRunning;
}
debugCountdown() {
this.logDebugCountdown = true;
}
}
//# sourceMappingURL=timer.js.map