@ronniepettersson/homebridge-dummy
Version:
Create Homebridge accessories to help with automation and control — scheduling, delays, sensors, commands, webhooks, and more
95 lines • 2.75 kB
JavaScript
import { TimeUnits } from '../model/enums.js';
export const SECOND = 1000;
export const MINUTE = 60 * SECOND;
export const HOUR = 60 * MINUTE;
export const DAY = 24 * HOUR;
export function DelayLogStrings(milliseconds, seconds, minutes, hours) {
return { milliseconds: milliseconds, seconds: seconds, minutes: minutes, hours: hours };
}
export function getDelay(rawTime, units, random = undefined, logStrings = undefined, log = undefined, caller = undefined) {
let time;
switch (units) {
case TimeUnits.MILLISECONDS:
time = rawTime;
break;
case TimeUnits.SECONDS:
time = rawTime * SECOND;
break;
case TimeUnits.MINUTES:
time = rawTime * MINUTE;
break;
case TimeUnits.HOURS:
time = rawTime * HOUR;
break;
}
if (random) {
time = Math.floor(Math.max(1, Math.random() * time));
if (time < SECOND) {
units = TimeUnits.MILLISECONDS;
}
else if (time < MINUTE) {
units = TimeUnits.SECONDS;
}
else if (time < HOUR) {
units = TimeUnits.MINUTES;
}
}
if (logStrings === undefined || log === undefined) {
return time;
}
let string;
let divisor;
switch (units) {
case TimeUnits.MILLISECONDS:
string = logStrings?.milliseconds;
divisor = 1;
break;
case TimeUnits.SECONDS:
string = logStrings?.seconds;
divisor = SECOND;
break;
case TimeUnits.MINUTES:
string = logStrings?.minutes;
divisor = MINUTE;
break;
case TimeUnits.HOURS:
string = logStrings?.hours;
divisor = HOUR;
break;
}
if (string) {
log.always(string, caller, Math.round(time / divisor));
}
return time;
}
export class Timeout {
caller;
log;
disableLogging;
timeout;
constructor(caller, log, disableLogging) {
this.caller = caller;
this.log = log;
this.disableLogging = disableLogging;
}
cancel() {
this.reset();
}
teardown() {
this.reset();
}
reset() {
clearTimeout(this.timeout);
this.timeout = undefined;
}
getDelay(rawTime, units, random = undefined, logStrings = undefined) {
return getDelay(rawTime, units, random, logStrings, this.disableLogging ? undefined : this.log, this.caller);
}
logIfDesired(message, ...parameters) {
if (this.disableLogging) {
return;
}
this.log.always(message, this.caller, ...parameters);
}
}
//# sourceMappingURL=timeout.js.map