node-red-contrib-looptimer-advanced 0.0.12 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,194 +1,455 @@
1
1
  module.exports = function (RED) {
2
2
  "use strict";
3
- var Looper = require('loop');
4
-
5
- var unitMap = [
6
- { unit: "Millisecond", multiplier: 1, duration: 1 },
7
- { unit: "Second", multiplier: 1000, get duration() { return unitMap[0].duration * unitMap[1].multiplier } },
8
- { unit: "Minute", multiplier: 60, get duration() { return unitMap[1].duration * unitMap[2].multiplier } },
9
- { unit: "Hour", multiplier: 60, get duration() { return unitMap[2].duration * unitMap[3].multiplier } },
10
- { unit: "Day", multiplier: 24, get duration() { return unitMap[3].duration * unitMap[4].multiplier } }
11
- ]
12
-
13
- var CalcDuration = function (unit, duration) {
14
- const unitObj = unitMap.find(o => o.unit === unit);
15
- if (!unitObj) {
3
+
4
+ const UNIT_MS = {
5
+ Millisecond: 1,
6
+ Second: 1000,
7
+ Minute: 60 * 1000,
8
+ Hour: 60 * 60 * 1000,
9
+ Day: 24 * 60 * 60 * 1000
10
+ };
11
+ const UNIT_LIST = Object.keys(UNIT_MS).join(", ");
12
+
13
+ // Settings that can be a msg., flow., global. or env. value instead of a number (typed inputs).
14
+ const TYPED_FIELDS = ["duration", "maxloops", "maxtimeout"];
15
+
16
+ function toMs(unit, amount) {
17
+ if (!Object.prototype.hasOwnProperty.call(UNIT_MS, unit)) {
16
18
  throw new Error(`Invalid unit: ${unit}`);
17
19
  }
18
- return unitObj.duration * duration;
19
- };
20
- function LoopTimer(n) {
21
- RED.nodes.createNode(this, n);
22
-
23
- this.units = n.units || "Second";
24
- this.duration = n.duration || 5;
25
- this.maxloops = n.maxloops || 100;
26
- this.maxtimeoutunits = n.maxtimeoutunits || "Hour";
27
- this.maxtimeout = n.maxtimeout || 1;
28
- this.nodeduration = n.nodeduration || 1;
29
- this.nodemaxtimeout = n.nodemaxtimeout || 1;
30
-
31
- if (this.duration <= 0) {
32
- this.duration = 0;
33
- }
34
-
35
- if (this.maxtimeout <= 0) {
36
- this.maxtimeout = 0;
37
- }
38
-
39
- var node = this;
40
- var loop = null;
41
- var timeout = null;
42
- var stopped = false;
43
- var cpmsg = null;
44
- var stopmsg = null;
45
- var mlmsg = null;
46
- var tomsg = null;
47
-
48
- this.on("input", function (msg) {
49
- loop = Looper();
50
- if (msg.loop != undefined) {
51
-
52
- if (msg.loop.units != undefined) {
53
- if ((msg.loop.units === "Millisecond") || (msg.loop.units === "Second") || (msg.loop.units === "Minute") || (msg.loop.units === "Hour") || (msg.loop.units === "Day")) {
54
- node.units = msg.loop.units;
55
- } else {
56
- node.status({ fill: "red", shape: "ring", text: "Invalid Attribute msg.loop.units" });
57
- node.error('Invalid Attribute: msg.loop.units, allowed values are Millisecond, Second, Minute, Hour, and Day');
58
- return;
59
- }
60
- }
20
+ return UNIT_MS[unit] * amount;
21
+ }
61
22
 
23
+ function isCommand(value, word) {
24
+ return typeof value === "string" && value.toLowerCase() === word;
25
+ }
62
26
 
63
- if (msg.loop.duration != undefined) {
64
- if (typeof msg.loop.duration === 'number') {
65
- node.duration = msg.loop.duration;
66
- } else {
67
- node.status({ fill: "red", shape: "ring", text: "msg.loop.units must be an Integer" });
68
- node.error('Invalid Attribute: msg.loop.duration, value must be an Integer');
69
- return;
70
- }
27
+ function LoopTimer(config) {
28
+ RED.nodes.createNode(this, config);
29
+ const node = this;
30
+
31
+ // Which settings are not plain numbers, the value then is the name of the msg/flow/global/env property.
32
+ const types = {};
33
+ TYPED_FIELDS.forEach((field) => { types[field] = config[field + "Type"] || "num"; });
34
+ const hasTyped = TYPED_FIELDS.some((field) => types[field] !== "num");
35
+
36
+ node.units = config.units || "Second";
37
+ node.duration = types.duration === "num" ? (config.duration || 5) : 5;
38
+ node.maxloops = types.maxloops === "num" ? (config.maxloops || 100) : 100;
39
+ node.maxtimeoutunits = config.maxtimeoutunits || "Hour";
40
+ node.maxtimeout = types.maxtimeout === "num" ? (config.maxtimeout || 1) : 1;
41
+
42
+ // Opt-in features. Flows saved by 0.0.x / 1.0.x do not carry these properties, so they keep the old behaviour.
43
+ node.totalcount = config.totalcount === true || config.totalcount === "true";
44
+ node.pausecontrol = config.pausecontrol === true || config.pausecontrol === "true";
45
+ node.sendfirst = !(config.sendfirst === false || config.sendfirst === "false");
46
+ node.addstate = config.addstate === true || config.addstate === "true";
47
+ node.concurrency = config.concurrency === "ignore" || config.concurrency === "pertopic" ? config.concurrency : "restart";
48
+ node.pausetimeout = Number(config.pausetimeout) > 0 ? Number(config.pausetimeout) : 0;
49
+ node.pausetimeoutunits = Object.prototype.hasOwnProperty.call(UNIT_MS, config.pausetimeoutunits) ? config.pausetimeoutunits : "Minute";
50
+ node.pauseaction = config.pauseaction === "stop" ? "stop" : "resume";
51
+
52
+ if (node.duration <= 0) { node.duration = 0; }
53
+ if (node.maxtimeout <= 0) { node.maxtimeout = 0; }
54
+
55
+ // Runtime state of the running loops: one per node, or one per msg.topic in "pertopic" mode.
56
+ const runs = new Map();
57
+
58
+ function keyOf(msg) {
59
+ return node.concurrency === "pertopic" ? String(msg.topic) : "";
60
+ }
61
+
62
+ // In "pertopic" mode the status shows all loops, not the last event.
63
+ function setStatus(fill, shape, text) {
64
+ if (node.concurrency === "pertopic" && runs.size > 0) {
65
+ let paused = 0;
66
+ runs.forEach((r) => { if (r.paused) { paused++; } });
67
+ const running = runs.size - paused;
68
+ node.status({
69
+ fill: running > 0 ? "green" : "yellow",
70
+ shape: "dot",
71
+ text: paused > 0 ? `${running} running, ${paused} paused` : `${running} running`
72
+ });
73
+ } else {
74
+ node.status({ fill: fill, shape: shape, text: text });
75
+ }
76
+ }
77
+
78
+ function clearTimers(run) {
79
+ if (run.timer) { clearTimeout(run.timer); run.timer = null; }
80
+ if (run.pauseTimer) { clearTimeout(run.pauseTimer); run.pauseTimer = null; }
81
+ }
82
+
83
+ function endLoop(run) {
84
+ clearTimers(run);
85
+ if (runs.get(run.key) === run) { runs.delete(run.key); }
86
+ }
87
+
88
+ // Counters of a loop, sent in msg.loopstate
89
+ function stateOf(run, state) {
90
+ const now = run.paused ? run.pausedAt : Date.now();
91
+ return {
92
+ state: state || (run.paused ? "paused" : "running"),
93
+ count: run.count,
94
+ sent: run.sent,
95
+ max: run.limit > 0 ? run.limit : null,
96
+ remaining: run.limit > 0 ? Math.max(0, run.limit - run.count) : null,
97
+ elapsed: now - run.t0,
98
+ interval: run.duration
99
+ };
100
+ }
101
+
102
+ // Copy of the message of the loop, with the loop counters when they are switched on
103
+ function copyOf(run, state) {
104
+ const m = RED.util.cloneMessage(run.msg);
105
+ if (run.addstate) { m.loopstate = stateOf(run, state); }
106
+ return m;
107
+ }
108
+
109
+ // Status message for the second output. Based on the message of the loop, or on the incoming one when there is no loop.
110
+ function controlMsg(base, payload, run, state, reason) {
111
+ const m = RED.util.cloneMessage(base);
112
+ m.payload = payload;
113
+ if (run && run.addstate) { m.loopstate = stateOf(run, state); }
114
+ if (reason) { m.reason = reason; }
115
+ return m;
116
+ }
117
+
118
+ function sendControl(base, payload, run, state, reason) {
119
+ node.send([null, controlMsg(base, payload, run, state, reason)]);
120
+ }
121
+
122
+ // Arms the single timer: either the next loop tick or, when it comes first, the overall timeout.
123
+ // Every tick is due at a fixed time after the start, so the loop does not drift.
124
+ function schedule(run) {
125
+ const tickDue = run.origin + (run.count + 1) * run.duration;
126
+ const deadline = run.t0 + run.maxtimeout;
127
+ const deadlineFirst = deadline < tickDue;
128
+ const due = deadlineFirst ? deadline : tickDue;
129
+ run.timer = setTimeout(deadlineFirst ? () => onDeadline(run) : () => onTick(run), Math.max(0, due - Date.now()));
130
+ }
131
+
132
+ function onDeadline(run) {
133
+ run.timer = null;
134
+ setStatus("red", "ring", "timeout reached");
135
+ sendControl(run.msg, "timeout", run, "finished");
136
+ endLoop(run);
137
+ }
138
+
139
+ function onTick(run) {
140
+ run.timer = null;
141
+ const now = Date.now();
142
+ const lateness = now - (run.origin + (run.count + 1) * run.duration);
143
+ run.count++;
144
+ run.sent++;
145
+ const count = run.count;
146
+ // After a long stall (e.g. a blocked event loop) the loop carries on from now instead of firing a burst
147
+ if (lateness > run.duration) { run.origin = now - count * run.duration; }
148
+
149
+ const cp = copyOf(run);
150
+ if (run.pausedFor) {
151
+ cp.pauseduration = run.pausedFor;
152
+ run.pausedFor = 0;
153
+ }
154
+
155
+ if (run.limit > 0 && count >= run.limit) {
156
+ node.send([cp, controlMsg(run.msg, "max loops reached", run, "finished")]);
157
+ setStatus("red", "ring", "max loops reached");
158
+ endLoop(run);
159
+ return;
160
+ }
161
+
162
+ if (count * run.duration <= run.maxtimeout) {
163
+ node.send([cp, null]);
164
+ if ((count + 1) * run.duration > run.maxtimeout) {
165
+ // Kept from 0.0.x: the last loop message is repeated together with the "timeout" message.
166
+ node.send([cp, controlMsg(run.msg, "timeout", run, "finished")]);
167
+ setStatus("red", "ring", "timeout reached");
168
+ endLoop(run);
169
+ return;
71
170
  }
171
+ setStatus("green", "dot", "running");
172
+ schedule(run);
173
+ } else {
174
+ setStatus("red", "ring", "timeout reached");
175
+ sendControl(run.msg, "timeout", run, "finished");
176
+ endLoop(run);
177
+ }
178
+ }
72
179
 
73
- if (msg.loop.maxtimeoutunits != undefined) {
74
- if ((msg.loop.maxtimeoutunits === "Millisecond") || (msg.loop.maxtimeoutunits === "Second") || (msg.loop.maxtimeoutunits === "Minute") || (msg.loop.maxtimeoutunits === "Hour") || (msg.loop.maxtimeoutunits === "Day")) {
75
- node.maxtimeoutunits = msg.loop.maxtimeoutunits;
76
- } else {
77
- node.status({ fill: "red", shape: "ring", text: "Invalid Attribute msg.loop.maxtimeoutunits" });
78
- node.error('Invalid Attribute: msg.loop.maxtimeoutunits, allowed values are Millisecond, Second, Minute, Hour, and Day');
79
- return;
80
- }
180
+ function stop(msg, run, reason) {
181
+ let state = null;
182
+ if (run) {
183
+ state = stateOf(run, "stopped");
184
+ endLoop(run);
185
+ }
186
+ setStatus("red", "ring", "stopped");
187
+ const m = controlMsg(msg, "stopped", null, null, reason);
188
+ if (run && run.addstate) { m.loopstate = state; }
189
+ node.send([null, m]);
190
+ }
191
+
192
+ function pause(run, msg) {
193
+ if (run.paused) { return; }
194
+ clearTimers(run);
195
+ run.paused = true;
196
+ run.pausedAt = Date.now();
197
+ setStatus("yellow", "ring", "paused");
198
+ sendControl(msg, "paused", run);
199
+ if (node.pausetimeout > 0) {
200
+ const wait = toMs(node.pausetimeoutunits, node.pausetimeout);
201
+ const action = node.pauseaction;
202
+ run.pauseTimer = setTimeout(() => {
203
+ run.pauseTimer = null;
204
+ if (action === "stop") { stop(run.msg, run, "pause timeout"); } else { resume(run, run.msg, "pause timeout"); }
205
+ }, wait);
206
+ }
207
+ }
208
+
209
+ function resume(run, msg, reason) {
210
+ if (!run.paused) { return; }
211
+ if (run.pauseTimer) { clearTimeout(run.pauseTimer); run.pauseTimer = null; }
212
+ // The time spent paused does not count: the ticks and the timeout continue where they were left
213
+ const spent = Date.now() - run.pausedAt;
214
+ run.origin += spent;
215
+ run.t0 += spent;
216
+ run.pausedFor += spent;
217
+ run.paused = false;
218
+ setStatus("green", "dot", "running");
219
+ sendControl(msg, "resumed", run, null, reason);
220
+ schedule(run);
221
+ }
222
+
223
+ // Validates and applies msg.loop overrides. Returns an error text, or null when everything is fine.
224
+ function applyOverrides(over) {
225
+ const checkUnit = (key, prop) => {
226
+ if (over[key] === undefined) { return null; }
227
+ if (!Object.prototype.hasOwnProperty.call(UNIT_MS, over[key])) {
228
+ node.status({ fill: "red", shape: "ring", text: `Invalid Attribute msg.loop.${key}` });
229
+ return `Invalid Attribute: msg.loop.${key}, allowed values are ${UNIT_LIST}`;
230
+ }
231
+ node[prop] = over[key];
232
+ return null;
233
+ };
234
+ const checkNumber = (key, prop) => {
235
+ if (over[key] === undefined) { return null; }
236
+ if (typeof over[key] !== "number" || isNaN(over[key])) {
237
+ node.status({ fill: "red", shape: "ring", text: `msg.loop.${key} must be a number` });
238
+ return `Invalid Attribute: msg.loop.${key}, value must be a number`;
239
+ }
240
+ node[prop] = over[key];
241
+ return null;
242
+ };
243
+ const checkBoolean = (key, prop) => {
244
+ if (over[key] === undefined) { return null; }
245
+ if (typeof over[key] !== "boolean") {
246
+ node.status({ fill: "red", shape: "ring", text: `msg.loop.${key} must be a boolean` });
247
+ return `Invalid Attribute: msg.loop.${key}, value must be a boolean`;
81
248
  }
249
+ node[prop] = over[key];
250
+ return null;
251
+ };
252
+ const checkAction = () => {
253
+ if (over.pauseaction === undefined) { return null; }
254
+ if (over.pauseaction !== "resume" && over.pauseaction !== "stop") {
255
+ node.status({ fill: "red", shape: "ring", text: "Invalid Attribute msg.loop.pauseaction" });
256
+ return "Invalid Attribute: msg.loop.pauseaction, allowed values are resume and stop";
257
+ }
258
+ node.pauseaction = over.pauseaction;
259
+ return null;
260
+ };
261
+ return checkBoolean("totalcount", "totalcount") ||
262
+ checkUnit("units", "units") ||
263
+ checkNumber("duration", "duration") ||
264
+ checkUnit("maxtimeoutunits", "maxtimeoutunits") ||
265
+ checkNumber("maxtimeout", "maxtimeout") ||
266
+ checkNumber("maxloops", "maxloops") ||
267
+ checkBoolean("sendfirst", "sendfirst") ||
268
+ checkBoolean("loopstate", "addstate") ||
269
+ checkNumber("pausetimeout", "pausetimeout") ||
270
+ checkUnit("pausetimeoutunits", "pausetimeoutunits") ||
271
+ checkAction();
272
+ }
82
273
 
274
+ function start(msg) {
275
+ const key = keyOf(msg);
276
+ const previous = runs.get(key);
277
+ if (previous) { endLoop(previous); }
83
278
 
84
- if (msg.loop.maxtimeout != undefined) {
85
- if (typeof msg.loop.maxtimeout === 'number') {
86
- node.maxtimeout = msg.loop.maxtimeout;
87
- } else {
88
- node.status({ fill: "red", shape: "ring", text: "msg.loop.maxtimeout must be an Integer" });
89
- node.error('Invalid Attribute: msg.loop.maxtimeout, value must be an Integer');
90
- return;
91
- }
279
+ const duration = toMs(node.units, node.duration);
280
+ const maxtimeout = toMs(node.maxtimeoutunits, node.maxtimeout);
281
+ const maxloops = Number(node.maxloops);
282
+
283
+ // limit = number of loop messages after the first one; 0 means unlimited (until timeout or stop).
284
+ let limit = maxloops;
285
+ if (node.totalcount) {
286
+ // totalcount: maxloops is the total number of messages, first one included; -1 = unlimited.
287
+ limit = maxloops < 0 ? 0 : (node.sendfirst ? maxloops - 1 : maxloops);
288
+ if (maxloops === 0) {
289
+ setStatus("red", "ring", "max loops reached");
290
+ sendControl(msg, "max loops reached");
291
+ return;
92
292
  }
93
- if (msg.loop.maxloops != undefined) {
94
- if (typeof msg.loop.maxloops === 'number') {
95
- node.maxloops = msg.loop.maxloops;
96
- } else {
97
- node.status({ fill: "red", shape: "ring", text: "msg.loop.maxloops must be an Integer" });
98
- node.error('Invalid Attribute: msg.loop.maxloops, value must be an Integer');
99
- return;
100
- }
293
+ if (maxloops === 1 && node.sendfirst) {
294
+ node.send([RED.util.cloneMessage(msg), null]);
295
+ setStatus("red", "ring", "max loops reached");
296
+ sendControl(msg, "max loops reached");
297
+ return;
101
298
  }
299
+ }
102
300
 
301
+ const now = Date.now();
302
+ const run = {
303
+ key: key,
304
+ msg: msg,
305
+ duration: duration,
306
+ maxtimeout: maxtimeout,
307
+ limit: limit,
308
+ addstate: node.addstate,
309
+ count: 0,
310
+ sent: 0,
311
+ timer: null,
312
+ pauseTimer: null,
313
+ paused: false,
314
+ pausedAt: 0,
315
+ pausedFor: 0,
316
+ origin: now, // the ticks are due at origin + n * duration
317
+ t0: now // start of the loop, without the time spent paused; the timeout is counted from here
318
+ };
319
+ runs.set(key, run);
320
+ if (node.sendfirst) {
321
+ run.sent = 1;
322
+ node.send([copyOf(run), null]);
323
+ }
324
+ setStatus("green", "dot", "running");
325
+ schedule(run);
326
+ }
103
327
 
328
+ // Runs that a command is meant for: the one of this topic, or all of them with msg.loop.all
329
+ function targets(msg, over) {
330
+ if (over && over.all === true) { return Array.from(runs.values()); }
331
+ const run = runs.get(keyOf(msg));
332
+ return run ? [run] : [];
333
+ }
104
334
 
335
+ function reportStatus(msg, over) {
336
+ const list = targets(msg, over);
337
+ if (list.length === 0) {
338
+ const m = RED.util.cloneMessage(msg);
339
+ m.payload = "status";
340
+ m.loopstate = { state: "idle" };
341
+ node.send([null, m]);
342
+ return;
105
343
  }
106
- node.nodeduration = CalcDuration(node.units, node.duration);
107
- node.nodemaxtimeout = CalcDuration(node.maxtimeoutunits, node.maxtimeout);
344
+ list.forEach((run) => {
345
+ const m = RED.util.cloneMessage(run.msg);
346
+ m.payload = "status";
347
+ m.loopstate = stateOf(run);
348
+ node.send([null, m]);
349
+ });
350
+ }
108
351
 
109
- loop.setTimeout(node.nodemaxtimeout);
110
- loop.setMaxLoop(node.maxloops);
111
- node.status({});
352
+ function handle(msg, done) {
353
+ const over = msg.loop !== null && typeof msg.loop === "object" ? msg.loop : undefined;
354
+ const command = over && typeof over.command === "string" ? over.command.toLowerCase() : null;
355
+ const byPayload = (word) => node.pausecontrol && isCommand(msg.payload, word);
356
+
357
+ let action = "start";
358
+ if (command === "pause" || byPayload("pause")) {
359
+ action = "pause";
360
+ } else if (command === "resume" || byPayload("resume")) {
361
+ action = "resume";
362
+ } else if (command === "status" || byPayload("status")) {
363
+ action = "status";
364
+ } else if (command === "stop" || isCommand(msg.payload, "stop")) {
365
+ action = "stop";
366
+ }
367
+
368
+ // While a loop runs the new messages are not wanted, not even their settings
369
+ if (action === "start" && node.concurrency === "ignore" && runs.has(keyOf(msg))) {
370
+ done();
371
+ return;
372
+ }
112
373
 
113
- if (stopped === false || msg._timerpass !== true) {
114
- stopped = false;
115
- clearTimeout(timeout);
116
- timeout = null;
117
- if (typeof msg.payload === "string" && msg.payload.toLowerCase() === "stop") {
118
- node.status({
119
- fill: "red",
120
- shape: "ring",
121
- text: "stopped"
122
- });
123
- stopped = true;
124
- stopmsg = RED.util.cloneMessage(msg);
125
- stopmsg.payload = "stopped";
126
- node.send([null, stopmsg]);
127
- stopped = false;
128
- } else {
129
- cpmsg = RED.util.cloneMessage(msg);
130
- node.send([cpmsg, null]);
131
- msg._timerpass = true;
132
- loop.run(function (next, err, data) {
133
- node.status({
134
- fill: "green",
135
- shape: "dot",
136
- text: "running"
137
- });
138
- data++;
139
- timeout = setTimeout(function () {
140
- if (stopped === false) {
141
- cpmsg = RED.util.cloneMessage(msg);
142
- if (data == node.maxloops) {
143
- mlmsg = RED.util.cloneMessage(msg);
144
- mlmsg.payload = "max loops reached";
145
- node.send([cpmsg, mlmsg]);
146
- node.status({
147
- fill: "red",
148
- shape: "ring",
149
- text: "max loops reached"
150
- });
151
- timeout = null;
152
- next("break");
153
- } else {
154
- node.status({});
155
- if ((data * node.nodeduration) <= node.nodemaxtimeout) {
156
- node.send([cpmsg, null]);
157
- timeout = null;
158
- if (((data + 1) * node.nodeduration) > node.nodemaxtimeout) {
159
- stopmsg = RED.util.cloneMessage(msg);
160
- stopmsg.payload = 'timeout';
161
- node.send([cpmsg, stopmsg]);
162
- node.status({
163
- fill: "red",
164
- shape: "ring",
165
- text: "timeout reached"
166
- });
167
- next("break");
168
- } else {
169
- next(undefined, data);
170
- }
171
- } else {
172
- timeout = null;
173
- next("break");
174
- }
175
- }
176
- } else {
177
- timeout = null;
178
- next("break");
179
- }
180
- }, node.nodeduration);
181
- }, 0);
374
+ if (over) {
375
+ const problem = applyOverrides(over);
376
+ if (problem) {
377
+ node.error(problem, msg);
378
+ done();
379
+ return;
182
380
  }
183
381
  }
184
- });
185
- this.on("close", function () {
186
- stopped = false;
187
- if (timeout) {
188
- clearTimeout(timeout);
382
+
383
+ try {
384
+ switch (action) {
385
+ case "pause":
386
+ targets(msg, over).forEach((run) => pause(run, msg));
387
+ break;
388
+ case "resume":
389
+ targets(msg, over).forEach((run) => resume(run, msg));
390
+ break;
391
+ case "status":
392
+ reportStatus(msg, over);
393
+ break;
394
+ case "stop": {
395
+ const list = targets(msg, over);
396
+ if (list.length === 0) {
397
+ stop(msg, null);
398
+ } else {
399
+ list.forEach((run) => stop(msg, run));
400
+ }
401
+ break;
402
+ }
403
+ default:
404
+ start(msg);
405
+ }
406
+ done();
407
+ } catch (err) {
408
+ node.status({ fill: "red", shape: "ring", text: err.message });
409
+ done(err);
410
+ }
411
+ }
412
+
413
+ // Reads the settings that are msg., flow., global. or env. values
414
+ function resolveTyped(msg) {
415
+ return Promise.all(TYPED_FIELDS.filter((field) => types[field] !== "num").map((field) => new Promise((resolve, reject) => {
416
+ RED.util.evaluateNodeProperty(config[field], types[field], node, msg, (err, value) => {
417
+ const number = Number(value);
418
+ if (err || value === undefined || value === null || value === "" || !isFinite(number)) {
419
+ node.status({ fill: "red", shape: "ring", text: `${field} must be a number` });
420
+ reject(new Error(`Invalid value for ${field} (${types[field]}.${config[field]}), value must be a number`));
421
+ return;
422
+ }
423
+ node[field] = field === "duration" || field === "maxtimeout" ? Math.max(number, 0) : number;
424
+ resolve();
425
+ });
426
+ })));
427
+ }
428
+
429
+ // Messages are handled one after the other, also when a setting has to be read from the context first
430
+ let queue = Promise.resolve();
431
+
432
+ node.on("input", function (msg, send, done) {
433
+ done = done || function (err) { if (err) { node.error(err, msg); } };
434
+
435
+ if (!hasTyped) {
436
+ handle(msg, done);
437
+ return;
189
438
  }
439
+ queue = queue
440
+ .then(() => resolveTyped(msg))
441
+ .then(() => handle(msg, done), (err) => {
442
+ node.error(err.message, msg);
443
+ done();
444
+ });
445
+ });
446
+
447
+ node.on("close", function () {
448
+ runs.forEach((run) => clearTimers(run));
449
+ runs.clear();
190
450
  node.status({});
191
451
  });
192
452
  }
453
+
193
454
  RED.nodes.registerType("looptimer-advanced", LoopTimer);
194
- }
455
+ };