@ronniepettersson/homebridge-dummy
Version:
Create Homebridge accessories to help with automation and control — scheduling, delays, sensors, commands, webhooks, and more
71 lines • 2.51 kB
JavaScript
import { DelayLogStrings, SECOND, Timeout } from './timeout.js';
import { isValidTimeUnits, printableValues, TimeUnits } from '../model/enums.js';
import { strings } from '../i18n/i18n.js';
import { Storage } from '../tools/storage.js';
import { assert } from '../tools/validation.js';
export class Timer extends Timeout {
config;
callerId;
static new(config, callerId, callerName, log, disableLogging) {
if (!assert(log, callerName, config, 'delay', 'units')) {
return;
}
if (!isValidTimeUnits(config.units)) {
log.error(strings.timer.badUnits, callerName, `'${config.units}'`, printableValues(TimeUnits));
return;
}
return new Timer(config, callerId, callerName, log, disableLogging);
}
expiresTimestamp;
constructor(config, callerId, callerName, log, disableLogging) {
super(callerName, log, disableLogging);
this.config = config;
this.callerId = callerId;
this.expiresTimestamp = Storage.get(this.timerStorageKey);
}
get timerStorageKey() {
return `${this.callerId}:Timer`;
}
storeExpiresTimestamp(value) {
Storage.set(this.timerStorageKey, value);
}
start(callback) {
super.reset();
const logStrings = DelayLogStrings(strings.timer.setMilliseconds, strings.timer.setSeconds, strings.timer.setMinutes, strings.timer.setHours);
let delay;
if (this.expiresTimestamp !== undefined) {
const timeRemaining = this.expiresTimestamp - Date.now();
if (timeRemaining > 0) {
delay = timeRemaining;
this.logIfDesired(strings.timer.resume);
}
else {
delay = 0.1 * SECOND;
this.logIfDesired(strings.timer.expired);
}
}
else {
delay = this.getDelay(this.config.delay, this.config.units, this.config.random, logStrings);
this.storeExpiresTimestamp(Date.now() + delay);
}
this.timeout = setTimeout(async () => {
this.reset();
await callback();
}, delay);
}
reset() {
this.expiresTimestamp = undefined;
this.storeExpiresTimestamp(undefined);
super.reset();
}
cancel() {
if (this.timeout) {
this.logIfDesired(strings.timer.cancel);
}
super.cancel();
}
teardown() {
super.reset();
}
}
//# sourceMappingURL=timer.js.map