forked from rkoshak/openhab-rules-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deferred.js
executable file
·72 lines (64 loc) · 1.9 KB
/
deferred.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
const { TimerMgr } = require('openhab_rules_tools');
const { time, items } = require('openhab');
/**
* Class that can be used to schedule a command or update to be sent to an Item later.
*/
class Deferred {
/**
* Constructor
*/
constructor() {
this.timers = TimerMgr();
}
/**
* Implements the command or update.
* @param {string} name of the Item
* @param {string} value command or update to send
* @param {boolean} isCommand when true, value will be sent as a command, otherwise posted as an update
*/
#timerBodyGenerator(target, value, isCommand) {
const item = items.getItem(target);
return () => (isCommand) ? item.sendCommand(value) : item.postUpdate(value);
}
/**
* Creates a timer to command or update the update after a time. If the when
* is before now, sendCommand or postUpdate immediately.
* @param {string} target name of the Item to update or command
* @param {string} value command or update to sendGatekeeper
* @param {*} when time.toZDT compatible duration or date/time
* @param {boolean} isCommand when true value is sent as a command
*/
defer(target, value, when, isCommand) {
const triggerTime = time.toZDT(when);
if (triggerTime.isBefore(time.toZDT())) {
triggerTime = time.toZDT();
}
this.timers.cancel(target);
this.timers.check(target, triggerTime, this.#timerBodyGenerator(target, value, isCommand, when), false);
}
/**
* Cancels the deferred actions for target, if there is one.
* @param {string} target name of the Item
*/
cancel(target) {
this.timers.cancel(target);
}
/**
* Cancels all the deferred actions.
*/
cancelAll() {
this.timers.cancelAll();
}
}
/**
* Deferred is a way to schedule a simple command sometime in the future.
*
* @returns a new instance of Deferred
*/
function getDeferred() {
return new Deferred();
}
module.exports = {
Deferred,
getDeferred
}