node-red-contrib-looptimer-advanced 1.0.0 โ 1.1.1
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.
- package/README.md +62 -10
- package/looptimer_advanced.html +187 -100
- package/looptimer_advanced.js +347 -112
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -19,7 +19,12 @@
|
|
|
19
19
|
- ๐ **Repeat a message** once per interval (milliseconds to days) with an optional maximum loop count and maximum run time.
|
|
20
20
|
- ๐ **Stop** with a payload, **โธ pause and โถ resume** without losing the loop counter or the timeout budget.
|
|
21
21
|
- ๐งฉ **Reconfigure per message** with `msg.loop`: interval, limits and commands, no redeploy needed.
|
|
22
|
-
- ๐ฏ **Exact counts**: optionally make *Max Loops* mean the total number of messages, including a single call.
|
|
22
|
+
- ๐ฏ **Exact counts**: optionally make *Max Loops* mean the total number of messages, including a single call, and optionally skip the immediate first message.
|
|
23
|
+
- ๐ **Loop counters**: `msg.loopstate` with the count, the remaining loops and the elapsed time, and a `status` command to ask for them.
|
|
24
|
+
- ๐งต **One loop per topic**: run a separate loop for every `msg.topic` in one node, or ignore new messages while a loop runs.
|
|
25
|
+
- โฒ๏ธ **Pause timeout**: resume or stop automatically when a pause lasts too long.
|
|
26
|
+
- ๐ **Typed settings**: read the interval and the limits from `msg.`, `flow.`, `global.` or `env`.
|
|
27
|
+
- ๐ฏ **No drift**: every tick is due at a fixed time after the start, also after a pause.
|
|
23
28
|
- ๐งช **Tested and dependency free**: plain timers, an automated test suite and CI on Node.js 18 โ 24.
|
|
24
29
|
- ๐ **Backwards compatible**: flows built with 0.0.x keep working unchanged, every new feature is opt-in.
|
|
25
30
|
|
|
@@ -57,31 +62,45 @@ stateDiagram-v2
|
|
|
57
62
|
|
|
58
63
|
| Output | Sends |
|
|
59
64
|
|---|---|
|
|
60
|
-
| **1** | The original message immediately, then one copy per loop. The first copy after a resume carries `msg.pauseduration` (ms). |
|
|
61
|
-
| **2** | Status messages with these payloads: `stopped`, `max loops reached`, `timeout`, `paused`, `resumed`. |
|
|
65
|
+
| **1** | The original message immediately (unless switched off), then one copy per loop. The first copy after a resume carries `msg.pauseduration` (ms). With *Add the loop counters* every copy carries `msg.loopstate`. |
|
|
66
|
+
| **2** | Status messages with these payloads: `stopped`, `max loops reached`, `timeout`, `paused`, `resumed`, `status`. After an automatic resume or stop `msg.reason` is `pause timeout`. |
|
|
62
67
|
|
|
63
68
|
## Controlling the loop
|
|
64
69
|
|
|
65
70
|
| How | What it does |
|
|
66
71
|
|---|---|
|
|
67
72
|
| `msg.payload = "stop"` (or `"STOP"`) | Stops the loop |
|
|
68
|
-
| `msg.payload = "pause"` / `"resume"` | Pauses / resumes (enable *Pause / resume with payload* in the node) |
|
|
69
|
-
| `msg.loop.command = "stop"`, `"pause"` or `"
|
|
70
|
-
|
|
|
73
|
+
| `msg.payload = "pause"` / `"resume"` / `"status"` | Pauses / resumes / reports the state (enable *Pause / resume / status with payload* in the node) |
|
|
74
|
+
| `msg.loop.command = "stop"`, `"pause"`, `"resume"` or `"status"` | Same, but always available and independent of the payload |
|
|
75
|
+
| `msg.loop.all = true` | With a command: applies to all loops of the node (see [one loop per topic](#new-messages-while-a-loop-runs)) |
|
|
76
|
+
| Any other message | Starts the loop, or restarts it (see [New messages while a loop runs](#new-messages-while-a-loop-runs)) |
|
|
71
77
|
|
|
72
78
|
Pausing freezes the remaining time of the current interval, the loop counter and the timeout budget. Resuming continues from exactly there. Stopping while paused works too.
|
|
73
79
|
|
|
80
|
+
### Pause timeout
|
|
81
|
+
|
|
82
|
+
Set *Pause Timeout* (and *After Timeout*: resume or stop the loop) to get the loop going again, or end it, when a pause lasts too long. Output 2 then sends `resumed` / `stopped` with `msg.reason = "pause timeout"`. Resuming or stopping by hand cancels the timeout.
|
|
83
|
+
|
|
84
|
+
### Status command
|
|
85
|
+
|
|
86
|
+
A `status` command sends a message with payload `status` and [`msg.loopstate`](#loop-counters-msgloopstate) on output 2, for example to show the progress on a dashboard. When no loop is running `msg.loopstate.state` is `idle`.
|
|
87
|
+
|
|
74
88
|
## Overriding settings with `msg.loop`
|
|
75
89
|
|
|
76
90
|
| Property | Type | Description |
|
|
77
91
|
|---|---|---|
|
|
78
|
-
| `msg.loop.duration` | number | Loop interval |
|
|
92
|
+
| `msg.loop.duration` | number | Loop interval, must be greater than 0 (intervals and timeouts longer than ~24.8 days work too) |
|
|
79
93
|
| `msg.loop.units` | string | `Millisecond`, `Second`, `Minute`, `Hour`, `Day` |
|
|
80
94
|
| `msg.loop.maxloops` | number | Maximum number of loops |
|
|
81
95
|
| `msg.loop.totalcount` | boolean | *Max Loops* counts the first message too |
|
|
82
96
|
| `msg.loop.maxtimeout` | number | Maximum run time of the loop |
|
|
83
97
|
| `msg.loop.maxtimeoutunits` | string | Same units as above |
|
|
84
|
-
| `msg.loop.
|
|
98
|
+
| `msg.loop.sendfirst` | boolean | Send the first message immediately |
|
|
99
|
+
| `msg.loop.loopstate` | boolean | Add `msg.loopstate` to the messages |
|
|
100
|
+
| `msg.loop.pausetimeout` | number | Pause timeout (with `msg.loop.pausetimeoutunits`) |
|
|
101
|
+
| `msg.loop.pauseaction` | string | `resume` or `stop`, what happens after the pause timeout |
|
|
102
|
+
| `msg.loop.command` | string | `stop`, `pause`, `resume` or `status` |
|
|
103
|
+
| `msg.loop.all` | boolean | Apply a command to all loops |
|
|
85
104
|
|
|
86
105
|
```js
|
|
87
106
|
// Function node: loop every 30 seconds, at most 10 times
|
|
@@ -104,6 +123,35 @@ Tick **Max Loops counts the first message too** (or send `msg.loop.totalcount =
|
|
|
104
123
|
| `1` | 2 messages | **1 message** (a single call) |
|
|
105
124
|
| `5` | 6 messages | **5 messages** |
|
|
106
125
|
|
|
126
|
+
Without **Send the first message immediately** (or `msg.loop.sendfirst = false`) nothing goes out at the start, the first message follows after the first interval. *Max Loops* `5` then gives **5** messages, and with *counts the first message too* it is the same number.
|
|
127
|
+
|
|
128
|
+
## Loop counters (`msg.loopstate`)
|
|
129
|
+
|
|
130
|
+
Tick **Add the loop counters as msg.loopstate** (or send `msg.loop.loopstate = true`) and every message carries:
|
|
131
|
+
|
|
132
|
+
| Property | Meaning |
|
|
133
|
+
|---|---|
|
|
134
|
+
| `state` | `running`, `paused`, `stopped`, `finished` or `idle` |
|
|
135
|
+
| `count` | Loop messages sent, the first message not included |
|
|
136
|
+
| `sent` | All messages sent |
|
|
137
|
+
| `max`, `remaining` | Limit and loops left, `null` when unlimited |
|
|
138
|
+
| `elapsed` | Milliseconds the loop has been running, the time paused not included |
|
|
139
|
+
| `interval` | Loop interval in milliseconds |
|
|
140
|
+
|
|
141
|
+
## New messages while a loop runs
|
|
142
|
+
|
|
143
|
+
The setting **New message** decides what a message does that arrives while a loop is running:
|
|
144
|
+
|
|
145
|
+
| Setting | Behavior |
|
|
146
|
+
|---|---|
|
|
147
|
+
| **restarts the loop** (default) | The loop starts again from the beginning, as it always did |
|
|
148
|
+
| **is ignored while a loop runs** | The message and its `msg.loop` settings are dropped until the loop is over. `stop`, `pause`, `resume` and `status` still work |
|
|
149
|
+
| **starts a separate loop per msg.topic** | Every topic has its own loop, a new message restarts only the loop of its topic. Commands apply to the loop of the topic of the command message, or to all loops with `msg.loop.all = true`. The node status shows the number of loops |
|
|
150
|
+
|
|
151
|
+
## Typed settings
|
|
152
|
+
|
|
153
|
+
*Loop Every*, *Max Loops* and *Max Timeout* are typed inputs: next to a fixed number they can be read from `msg.`, `flow.`, `global.` or an environment variable (`env`). The value is read only for messages that start a loop (commands like `stop` do not need it), and has to be a number (the interval greater than 0), otherwise the node reports an error and does not start. Overrides in `msg.loop` are applied on top.
|
|
154
|
+
|
|
107
155
|
## Versioning
|
|
108
156
|
|
|
109
157
|
Since **1.0.0** the package follows [Semantic Versioning](https://semver.org/) and keeps a [changelog](CHANGELOG.md) in the [Keep a Changelog](https://keepachangelog.com/) format.
|
|
@@ -116,6 +164,10 @@ Since **1.0.0** the package follows [Semantic Versioning](https://semver.org/) a
|
|
|
116
164
|
|
|
117
165
|
Releases are tagged `vX.Y.Z` on GitHub. The old `0.0.x` numbering was one increment per change and carried no compatibility promise. `1.0.0` marks the first release with a stable, tested public interface: the node's properties, `msg.loop` and the output payloads.
|
|
118
166
|
|
|
167
|
+
## Upgrading
|
|
168
|
+
|
|
169
|
+
**From 1.0.x to 1.1:** nothing to change, every new setting is off by default and existing nodes keep their behavior. The only visible difference is that the ticks no longer drift: a long loop now sends its messages at fixed times after the start instead of a little later every time.
|
|
170
|
+
|
|
119
171
|
## Upgrading from 0.0.x
|
|
120
172
|
|
|
121
173
|
Nothing to change in your flows. What is different:
|
|
@@ -124,7 +176,7 @@ Nothing to change in your flows. What is different:
|
|
|
124
176
|
- A loop that hits its maximum timeout now always reports `timeout` on output 2 (before it sometimes ended silently). The old single-call workaround (`maxloops: 0` with a tiny `maxtimeout`) still works.
|
|
125
177
|
- Invalid `msg.loop` values are reported through normal error handling, so a **Catch** node sees them.
|
|
126
178
|
- Minimum versions: Node-RED 3.0 and Node.js 18.
|
|
127
|
-
- A payload of `pause` or `
|
|
179
|
+
- A payload of `pause`, `resume` or `status` is only treated as a command when the option is ticked. Existing nodes have it **off**, so such payloads loop like any other value.
|
|
128
180
|
|
|
129
181
|
## Contributing
|
|
130
182
|
|
|
@@ -139,4 +191,4 @@ npm test
|
|
|
139
191
|
|
|
140
192
|
## Credits and license
|
|
141
193
|
|
|
142
|
-
Based on **node-red-contrib-looptimer** and **node-red-contrib-looptimer2**, with the addition of per-message overrides, pause/resume and exact counting. Released under the [Apache-2.0 license](LICENSE).
|
|
194
|
+
Based on **node-red-contrib-looptimer** and **node-red-contrib-looptimer2**, with the addition of per-message overrides, pause/resume, loop counters, one loop per topic, typed settings and exact counting. Released under the [Apache-2.0 license](LICENSE).
|
package/looptimer_advanced.html
CHANGED
|
@@ -1,100 +1,187 @@
|
|
|
1
|
-
<script type="text/javascript">
|
|
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
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
<
|
|
82
|
-
<
|
|
83
|
-
<
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
<
|
|
87
|
-
<
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
<
|
|
91
|
-
|
|
92
|
-
<
|
|
93
|
-
<
|
|
94
|
-
</
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
</
|
|
1
|
+
<script type="text/javascript">
|
|
2
|
+
(function () {
|
|
3
|
+
// Settings can be a number, or a msg., flow., global. or env. value
|
|
4
|
+
function typedNumber(typeField) {
|
|
5
|
+
return function (value) {
|
|
6
|
+
if ((this[typeField] || 'num') !== 'num') { return !!value; }
|
|
7
|
+
return RED.validators.number()(value);
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
const numericTypes = ['num', 'msg', 'flow', 'global', 'env'];
|
|
11
|
+
|
|
12
|
+
RED.nodes.registerType('looptimer-advanced', {
|
|
13
|
+
category: 'function',
|
|
14
|
+
color: "#33B2FF",
|
|
15
|
+
defaults: {
|
|
16
|
+
duration: { value: "5", required: true, validate: typedNumber('durationType') },
|
|
17
|
+
durationType: { value: "num" },
|
|
18
|
+
units: { value: "Second" },
|
|
19
|
+
maxloops: { value: "100", required: false, validate: typedNumber('maxloopsType') },
|
|
20
|
+
maxloopsType: { value: "num" },
|
|
21
|
+
totalcount: { value: false },
|
|
22
|
+
sendfirst: { value: true },
|
|
23
|
+
maxtimeout: { value: "1", required: false, validate: typedNumber('maxtimeoutType') },
|
|
24
|
+
maxtimeoutType: { value: "num" },
|
|
25
|
+
maxtimeoutunits: { value: "Hour" },
|
|
26
|
+
concurrency: { value: "restart" },
|
|
27
|
+
pausecontrol: { value: true },
|
|
28
|
+
pausetimeout: { value: "", required: false, validate: function (v) { return v === undefined || v === "" || RED.validators.number()(v); } },
|
|
29
|
+
pausetimeoutunits: { value: "Minute" },
|
|
30
|
+
pauseaction: { value: "resume" },
|
|
31
|
+
addstate: { value: false },
|
|
32
|
+
name: { value: "" }
|
|
33
|
+
},
|
|
34
|
+
inputs: 1,
|
|
35
|
+
outputs: 2,
|
|
36
|
+
icon: "looptimer_advanced.png",
|
|
37
|
+
label: function () {
|
|
38
|
+
return this.name || this.duration + " " + this.units + " Loop";
|
|
39
|
+
},
|
|
40
|
+
labelStyle: function () {
|
|
41
|
+
return this.name ? "node_label_italic" : "";
|
|
42
|
+
},
|
|
43
|
+
outputLabels: ["original msg", "stopped msg"],
|
|
44
|
+
oneditprepare: function () {
|
|
45
|
+
// Nodes saved by earlier versions do not have the newer settings, show the defaults
|
|
46
|
+
const defaults = { durationType: 'num', maxloopsType: 'num', maxtimeoutType: 'num', concurrency: 'restart', pausetimeoutunits: 'Minute', pauseaction: 'resume' };
|
|
47
|
+
Object.keys(defaults).forEach((key) => {
|
|
48
|
+
if (!this[key]) { $('#node-input-' + key).val(defaults[key]); }
|
|
49
|
+
});
|
|
50
|
+
if (this.sendfirst === undefined) { $('#node-input-sendfirst').prop('checked', true); }
|
|
51
|
+
|
|
52
|
+
['duration', 'maxloops', 'maxtimeout'].forEach((field) => {
|
|
53
|
+
$('#node-input-' + field).typedInput({
|
|
54
|
+
default: 'num',
|
|
55
|
+
types: numericTypes,
|
|
56
|
+
typeField: '#node-input-' + field + 'Type'
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
$('#node-input-duration').typedInput('width', '150px');
|
|
60
|
+
$('#node-input-maxloops').typedInput('width', '150px');
|
|
61
|
+
$('#node-input-maxtimeout').typedInput('width', '150px');
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
})();
|
|
65
|
+
</script>
|
|
66
|
+
|
|
67
|
+
<script type="text/html" data-template-name="looptimer-advanced">
|
|
68
|
+
<div class="form-row">
|
|
69
|
+
<label for="node-input-duration"><i class="fa fa-clock-o"></i> Loop Every</label>
|
|
70
|
+
<input type="text" id="node-input-duration">
|
|
71
|
+
<input type="hidden" id="node-input-durationType">
|
|
72
|
+
<select id="node-input-units" style="width:120px !important">
|
|
73
|
+
<option value="Millisecond">Milliseconds</option>
|
|
74
|
+
<option value="Second">Seconds</option>
|
|
75
|
+
<option value="Minute">Minutes</option>
|
|
76
|
+
<option value="Hour">Hours</option>
|
|
77
|
+
<option value="Day">Days</option>
|
|
78
|
+
</select>
|
|
79
|
+
</div>
|
|
80
|
+
<div class="form-row">
|
|
81
|
+
<label for="node-input-maxloops"><i class="fa fa-repeat"></i> Max Loops</label>
|
|
82
|
+
<input type="text" id="node-input-maxloops">
|
|
83
|
+
<input type="hidden" id="node-input-maxloopsType">
|
|
84
|
+
</div>
|
|
85
|
+
<div class="form-row">
|
|
86
|
+
<label> </label>
|
|
87
|
+
<input type="checkbox" id="node-input-totalcount" style="display:inline-block; width:auto; vertical-align:top;">
|
|
88
|
+
<label for="node-input-totalcount" style="width:auto"> Max Loops counts the first message too</label>
|
|
89
|
+
</div>
|
|
90
|
+
<div class="form-row">
|
|
91
|
+
<label> </label>
|
|
92
|
+
<input type="checkbox" id="node-input-sendfirst" style="display:inline-block; width:auto; vertical-align:top;">
|
|
93
|
+
<label for="node-input-sendfirst" style="width:auto"> Send the first message immediately</label>
|
|
94
|
+
</div>
|
|
95
|
+
<div class="form-row">
|
|
96
|
+
<label for="node-input-maxtimeout"><i class="fa fa-clock-o"></i> Max Timeout</label>
|
|
97
|
+
<input type="text" id="node-input-maxtimeout">
|
|
98
|
+
<input type="hidden" id="node-input-maxtimeoutType">
|
|
99
|
+
<select id="node-input-maxtimeoutunits" style="width:120px !important">
|
|
100
|
+
<option value="Millisecond">Milliseconds</option>
|
|
101
|
+
<option value="Second">Seconds</option>
|
|
102
|
+
<option value="Minute">Minutes</option>
|
|
103
|
+
<option value="Hour">Hours</option>
|
|
104
|
+
<option value="Day">Days</option>
|
|
105
|
+
</select>
|
|
106
|
+
</div>
|
|
107
|
+
<div class="form-row">
|
|
108
|
+
<label for="node-input-concurrency"><i class="fa fa-random"></i> New message</label>
|
|
109
|
+
<select id="node-input-concurrency" style="width:270px !important">
|
|
110
|
+
<option value="restart">restarts the loop</option>
|
|
111
|
+
<option value="ignore">is ignored while a loop runs</option>
|
|
112
|
+
<option value="pertopic">starts a separate loop per msg.topic</option>
|
|
113
|
+
</select>
|
|
114
|
+
</div>
|
|
115
|
+
<div class="form-row">
|
|
116
|
+
<label> </label>
|
|
117
|
+
<input type="checkbox" id="node-input-pausecontrol" style="display:inline-block; width:auto; vertical-align:top;">
|
|
118
|
+
<label for="node-input-pausecontrol" style="width:auto"> Pause / resume / status with payload</label>
|
|
119
|
+
</div>
|
|
120
|
+
<div class="form-row">
|
|
121
|
+
<label for="node-input-pausetimeout"><i class="fa fa-pause"></i> Pause Timeout</label>
|
|
122
|
+
<input type="text" id="node-input-pausetimeout" placeholder="none" style="text-align:end; width:70px !important">
|
|
123
|
+
<select id="node-input-pausetimeoutunits" style="width:120px !important">
|
|
124
|
+
<option value="Millisecond">Milliseconds</option>
|
|
125
|
+
<option value="Second">Seconds</option>
|
|
126
|
+
<option value="Minute">Minutes</option>
|
|
127
|
+
<option value="Hour">Hours</option>
|
|
128
|
+
<option value="Day">Days</option>
|
|
129
|
+
</select>
|
|
130
|
+
</div>
|
|
131
|
+
<div class="form-row">
|
|
132
|
+
<label for="node-input-pauseaction"><i class="fa fa-step-forward"></i> After Timeout</label>
|
|
133
|
+
<select id="node-input-pauseaction" style="width:140px !important">
|
|
134
|
+
<option value="resume">resume the loop</option>
|
|
135
|
+
<option value="stop">stop the loop</option>
|
|
136
|
+
</select>
|
|
137
|
+
</div>
|
|
138
|
+
<div class="form-row">
|
|
139
|
+
<label> </label>
|
|
140
|
+
<input type="checkbox" id="node-input-addstate" style="display:inline-block; width:auto; vertical-align:top;">
|
|
141
|
+
<label for="node-input-addstate" style="width:auto"> Add the loop counters as msg.loopstate</label>
|
|
142
|
+
</div>
|
|
143
|
+
<div class="form-row">
|
|
144
|
+
<label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
|
|
145
|
+
<input type="text" id="node-input-name" placeholder="Name">
|
|
146
|
+
</div>
|
|
147
|
+
</script>
|
|
148
|
+
|
|
149
|
+
<script type="text/html" data-help-name="looptimer-advanced">
|
|
150
|
+
<p>Sends the <code>msg</code> through the first output, then repeats it once per the configured duration until it is stopped, the maximum number of loops is reached or the maximum timeout expires.</p>
|
|
151
|
+
|
|
152
|
+
<h3>Inputs</h3>
|
|
153
|
+
<dl class="message-properties">
|
|
154
|
+
<dt>payload <span class="property-type">string</span></dt>
|
|
155
|
+
<dd><code>stop</code> / <code>STOP</code> stops the loop. If enabled in the node, <code>pause</code>, <code>resume</code> and <code>status</code> do what they say. Any other message (re)starts the loop.</dd>
|
|
156
|
+
<dt class="optional">loop.command <span class="property-type">string</span></dt>
|
|
157
|
+
<dd><code>stop</code>, <code>pause</code>, <code>resume</code> or <code>status</code>. Works regardless of the payload and of the "Pause / resume / status with payload" setting.</dd>
|
|
158
|
+
<dt class="optional">loop.all <span class="property-type">boolean</span></dt>
|
|
159
|
+
<dd>With <code>true</code> a command applies to all loops of the node (see "New message" below).</dd>
|
|
160
|
+
<dt class="optional">loop.duration, loop.units <span class="property-type">number, string</span></dt>
|
|
161
|
+
<dd>Override the loop interval, which must be greater than 0. Units: <code>Millisecond</code>, <code>Second</code>, <code>Minute</code>, <code>Hour</code>, <code>Day</code>.</dd>
|
|
162
|
+
<dt class="optional">loop.maxtimeout, loop.maxtimeoutunits <span class="property-type">number, string</span></dt>
|
|
163
|
+
<dd>Override the maximum timeout.</dd>
|
|
164
|
+
<dt class="optional">loop.maxloops <span class="property-type">number</span></dt>
|
|
165
|
+
<dd>Override the maximum number of loops.</dd>
|
|
166
|
+
<dt class="optional">loop.totalcount, loop.sendfirst, loop.loopstate <span class="property-type">boolean</span></dt>
|
|
167
|
+
<dd>Override "Max Loops counts the first message too", "Send the first message immediately" and "Add the loop counters".</dd>
|
|
168
|
+
<dt class="optional">loop.pausetimeout, loop.pausetimeoutunits, loop.pauseaction <span class="property-type">number, string, string</span></dt>
|
|
169
|
+
<dd>Override the pause timeout and what happens after it (<code>resume</code> or <code>stop</code>).</dd>
|
|
170
|
+
</dl>
|
|
171
|
+
|
|
172
|
+
<h3>Outputs</h3>
|
|
173
|
+
<ol class="node-ports">
|
|
174
|
+
<li>The original message, then once per loop. After a pause, the first message carries <code>msg.pauseduration</code> (milliseconds spent paused). With "Add the loop counters" every message carries <code>msg.loopstate</code>.</li>
|
|
175
|
+
<li>Status messages with payload <code>stopped</code>, <code>max loops reached</code>, <code>timeout</code>, <code>paused</code>, <code>resumed</code> or <code>status</code>. After an automatic resume or stop <code>msg.reason</code> is <code>pause timeout</code>.</li>
|
|
176
|
+
</ol>
|
|
177
|
+
|
|
178
|
+
<h3>msg.loopstate</h3>
|
|
179
|
+
<p><code>state</code> (<code>running</code>, <code>paused</code>, <code>stopped</code>, <code>finished</code> or <code>idle</code>), <code>count</code> (loop messages sent, the first one not included), <code>sent</code> (all messages), <code>max</code> and <code>remaining</code> (<code>null</code> when unlimited), <code>elapsed</code> (milliseconds the loop has been running, the time paused not included) and <code>interval</code> (milliseconds).</p>
|
|
180
|
+
|
|
181
|
+
<h3>Details</h3>
|
|
182
|
+
<p><b>Counting.</b> By default the first message is not part of the loop, so Max Loops <code>5</code> gives <code>6</code> messages. Tick "Max Loops counts the first message too" to get exactly the configured number: <code>1</code> is a single message, <code>0</code> sends nothing and <code>-1</code> is unlimited. Without "Send the first message immediately" the first message goes out after the first interval, so Max Loops <code>5</code> gives <code>5</code> messages.</p>
|
|
183
|
+
<p><b>New message.</b> By default a new message restarts the loop. "is ignored while a loop runs" drops it (also its settings) until the loop is over. "starts a separate loop per msg.topic" runs one loop per topic, <code>stop</code>, <code>pause</code>, <code>resume</code> and <code>status</code> then apply to the loop of the topic of the command, or to all loops with <code>msg.loop.all = true</code>.</p>
|
|
184
|
+
<p><b>Pause.</b> Pausing freezes the remaining time of the current interval, the loop counter and the timeout budget. With a pause timeout the loop is resumed or stopped automatically after that time.</p>
|
|
185
|
+
<p><b>Typed settings.</b> Loop Every, Max Loops and Max Timeout can be read from <code>msg.</code>, <code>flow.</code>, <code>global.</code> or <code>env</code> instead of being a fixed number. They are only read for messages that start a loop, commands like <code>stop</code> do not need them. The interval has to be greater than 0.</p>
|
|
186
|
+
<p>Overrides in <code>msg.loop</code> stay in effect for the following messages.</p>
|
|
187
|
+
</script>
|
package/looptimer_advanced.js
CHANGED
|
@@ -10,6 +10,12 @@ module.exports = function (RED) {
|
|
|
10
10
|
};
|
|
11
11
|
const UNIT_LIST = Object.keys(UNIT_MS).join(", ");
|
|
12
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
|
+
// setTimeout runs a delay above this after 1 ms (32-bit overflow), so longer waits are split into chunks.
|
|
17
|
+
const MAX_DELAY = 2147483647;
|
|
18
|
+
|
|
13
19
|
function toMs(unit, amount) {
|
|
14
20
|
if (!Object.prototype.hasOwnProperty.call(UNIT_MS, unit)) {
|
|
15
21
|
throw new Error(`Invalid unit: ${unit}`);
|
|
@@ -25,77 +31,145 @@ module.exports = function (RED) {
|
|
|
25
31
|
RED.nodes.createNode(this, config);
|
|
26
32
|
const node = this;
|
|
27
33
|
|
|
34
|
+
// Which settings are not plain numbers, the value then is the name of the msg/flow/global/env property.
|
|
35
|
+
const types = {};
|
|
36
|
+
TYPED_FIELDS.forEach((field) => { types[field] = config[field + "Type"] || "num"; });
|
|
37
|
+
const hasTyped = TYPED_FIELDS.some((field) => types[field] !== "num");
|
|
38
|
+
|
|
28
39
|
node.units = config.units || "Second";
|
|
29
|
-
|
|
30
|
-
|
|
40
|
+
// The loop interval has to be a finite number > 0, anything else falls back to the default
|
|
41
|
+
const configDuration = Number(config.duration || 5);
|
|
42
|
+
node.duration = types.duration === "num" && isFinite(configDuration) && configDuration > 0 ? configDuration : 5;
|
|
43
|
+
node.maxloops = types.maxloops === "num" ? (config.maxloops || 100) : 100;
|
|
31
44
|
node.maxtimeoutunits = config.maxtimeoutunits || "Hour";
|
|
32
|
-
node.maxtimeout = config.maxtimeout || 1;
|
|
33
|
-
|
|
45
|
+
node.maxtimeout = types.maxtimeout === "num" ? (config.maxtimeout || 1) : 1;
|
|
46
|
+
|
|
47
|
+
// Opt-in features. Flows saved by 0.0.x / 1.0.x do not carry these properties, so they keep the old behaviour.
|
|
34
48
|
node.totalcount = config.totalcount === true || config.totalcount === "true";
|
|
35
49
|
node.pausecontrol = config.pausecontrol === true || config.pausecontrol === "true";
|
|
50
|
+
node.sendfirst = !(config.sendfirst === false || config.sendfirst === "false");
|
|
51
|
+
node.addstate = config.addstate === true || config.addstate === "true";
|
|
52
|
+
node.concurrency = config.concurrency === "ignore" || config.concurrency === "pertopic" ? config.concurrency : "restart";
|
|
53
|
+
node.pausetimeout = Number(config.pausetimeout) > 0 ? Number(config.pausetimeout) : 0;
|
|
54
|
+
node.pausetimeoutunits = Object.prototype.hasOwnProperty.call(UNIT_MS, config.pausetimeoutunits) ? config.pausetimeoutunits : "Minute";
|
|
55
|
+
node.pauseaction = config.pauseaction === "stop" ? "stop" : "resume";
|
|
36
56
|
|
|
37
|
-
if (node.duration <= 0) { node.duration = 0; }
|
|
38
57
|
if (node.maxtimeout <= 0) { node.maxtimeout = 0; }
|
|
39
58
|
|
|
40
|
-
// Runtime state of the running
|
|
41
|
-
|
|
59
|
+
// Runtime state of the running loops: one per node, or one per msg.topic in "pertopic" mode.
|
|
60
|
+
const runs = new Map();
|
|
61
|
+
|
|
62
|
+
function keyOf(msg) {
|
|
63
|
+
return node.concurrency === "pertopic" ? String(msg.topic) : "";
|
|
64
|
+
}
|
|
42
65
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
66
|
+
// In "pertopic" mode the status shows all loops, not the last event.
|
|
67
|
+
function setStatus(fill, shape, text) {
|
|
68
|
+
if (node.concurrency === "pertopic" && runs.size > 0) {
|
|
69
|
+
let paused = 0;
|
|
70
|
+
runs.forEach((r) => { if (r.paused) { paused++; } });
|
|
71
|
+
const running = runs.size - paused;
|
|
72
|
+
node.status({
|
|
73
|
+
fill: running > 0 ? "green" : "yellow",
|
|
74
|
+
shape: "dot",
|
|
75
|
+
text: paused > 0 ? `${running} running, ${paused} paused` : `${running} running`
|
|
76
|
+
});
|
|
77
|
+
} else {
|
|
78
|
+
node.status({ fill: fill, shape: shape, text: text });
|
|
47
79
|
}
|
|
48
80
|
}
|
|
49
81
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
82
|
+
// Calls fn at the absolute time due, also when that is more than MAX_DELAY away. The timer is run[prop].
|
|
83
|
+
function armAt(run, prop, due, fn) {
|
|
84
|
+
const left = due - Date.now();
|
|
85
|
+
if (left > MAX_DELAY) {
|
|
86
|
+
run[prop] = setTimeout(() => armAt(run, prop, due, fn), MAX_DELAY);
|
|
87
|
+
} else {
|
|
88
|
+
run[prop] = setTimeout(fn, Math.max(0, left));
|
|
89
|
+
}
|
|
53
90
|
}
|
|
54
91
|
|
|
55
|
-
function
|
|
56
|
-
|
|
92
|
+
function clearTimers(run) {
|
|
93
|
+
if (run.timer) { clearTimeout(run.timer); run.timer = null; }
|
|
94
|
+
if (run.pauseTimer) { clearTimeout(run.pauseTimer); run.pauseTimer = null; }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function endLoop(run) {
|
|
98
|
+
clearTimers(run);
|
|
99
|
+
if (runs.get(run.key) === run) { runs.delete(run.key); }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Counters of a loop, sent in msg.loopstate
|
|
103
|
+
function stateOf(run, state) {
|
|
104
|
+
const now = run.paused ? run.pausedAt : Date.now();
|
|
105
|
+
return {
|
|
106
|
+
state: state || (run.paused ? "paused" : "running"),
|
|
107
|
+
count: run.count,
|
|
108
|
+
sent: run.sent,
|
|
109
|
+
max: run.limit > 0 ? run.limit : null,
|
|
110
|
+
remaining: run.limit > 0 ? Math.max(0, run.limit - run.count) : null,
|
|
111
|
+
elapsed: now - run.t0,
|
|
112
|
+
interval: run.duration
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Copy of the message of the loop, with the loop counters when they are switched on
|
|
117
|
+
function copyOf(run, state) {
|
|
118
|
+
const m = RED.util.cloneMessage(run.msg);
|
|
119
|
+
if (run.addstate) { m.loopstate = stateOf(run, state); }
|
|
120
|
+
return m;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Status message for the second output. Based on the message of the loop, or on the incoming one when there is no loop.
|
|
124
|
+
function controlMsg(base, payload, run, state, reason) {
|
|
125
|
+
const m = RED.util.cloneMessage(base);
|
|
57
126
|
m.payload = payload;
|
|
58
|
-
|
|
127
|
+
if (run && run.addstate) { m.loopstate = stateOf(run, state); }
|
|
128
|
+
if (reason) { m.reason = reason; }
|
|
129
|
+
return m;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function sendControl(base, payload, run, state, reason) {
|
|
133
|
+
node.send([null, controlMsg(base, payload, run, state, reason)]);
|
|
59
134
|
}
|
|
60
135
|
|
|
61
136
|
// Arms the single timer: either the next loop tick or, when it comes first, the overall timeout.
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const deadlineFirst = untilDeadline < untilTick;
|
|
70
|
-
const delay = Math.max(0, Math.min(untilTick, untilDeadline));
|
|
71
|
-
run.tickDue = now + (deadlineFirst ? untilTick : delay);
|
|
72
|
-
run.deadline = now + untilDeadline;
|
|
73
|
-
run.timer = setTimeout(deadlineFirst ? onDeadline : onTick, delay);
|
|
137
|
+
// Every tick is due at a fixed time after the start, so the loop does not drift.
|
|
138
|
+
function schedule(run) {
|
|
139
|
+
const tickDue = run.origin + (run.count + 1) * run.duration;
|
|
140
|
+
const deadline = run.t0 + run.maxtimeout;
|
|
141
|
+
const deadlineFirst = deadline < tickDue;
|
|
142
|
+
const due = deadlineFirst ? deadline : tickDue;
|
|
143
|
+
armAt(run, "timer", due, deadlineFirst ? () => onDeadline(run) : () => onTick(run));
|
|
74
144
|
}
|
|
75
145
|
|
|
76
|
-
function onDeadline() {
|
|
146
|
+
function onDeadline(run) {
|
|
77
147
|
run.timer = null;
|
|
78
|
-
|
|
79
|
-
sendControl(run.msg, "timeout");
|
|
80
|
-
endLoop();
|
|
148
|
+
setStatus("red", "ring", "timeout reached");
|
|
149
|
+
sendControl(run.msg, "timeout", run, "finished");
|
|
150
|
+
endLoop(run);
|
|
81
151
|
}
|
|
82
152
|
|
|
83
|
-
function onTick() {
|
|
153
|
+
function onTick(run) {
|
|
84
154
|
run.timer = null;
|
|
155
|
+
const now = Date.now();
|
|
156
|
+
const lateness = now - (run.origin + (run.count + 1) * run.duration);
|
|
85
157
|
run.count++;
|
|
158
|
+
run.sent++;
|
|
86
159
|
const count = run.count;
|
|
87
|
-
|
|
160
|
+
// After a long stall (e.g. a blocked event loop) the loop carries on from now instead of firing a burst
|
|
161
|
+
if (lateness > run.duration) { run.origin = now - count * run.duration; }
|
|
162
|
+
|
|
163
|
+
const cp = copyOf(run);
|
|
88
164
|
if (run.pausedFor) {
|
|
89
165
|
cp.pauseduration = run.pausedFor;
|
|
90
166
|
run.pausedFor = 0;
|
|
91
167
|
}
|
|
92
168
|
|
|
93
169
|
if (run.limit > 0 && count >= run.limit) {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
node.status({ fill: "red", shape: "ring", text: "max loops reached" });
|
|
98
|
-
endLoop();
|
|
170
|
+
node.send([cp, controlMsg(run.msg, "max loops reached", run, "finished")]);
|
|
171
|
+
setStatus("red", "ring", "max loops reached");
|
|
172
|
+
endLoop(run);
|
|
99
173
|
return;
|
|
100
174
|
}
|
|
101
175
|
|
|
@@ -103,85 +177,128 @@ module.exports = function (RED) {
|
|
|
103
177
|
node.send([cp, null]);
|
|
104
178
|
if ((count + 1) * run.duration > run.maxtimeout) {
|
|
105
179
|
// Kept from 0.0.x: the last loop message is repeated together with the "timeout" message.
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
node.status({ fill: "red", shape: "ring", text: "timeout reached" });
|
|
110
|
-
endLoop();
|
|
180
|
+
node.send([cp, controlMsg(run.msg, "timeout", run, "finished")]);
|
|
181
|
+
setStatus("red", "ring", "timeout reached");
|
|
182
|
+
endLoop(run);
|
|
111
183
|
return;
|
|
112
184
|
}
|
|
113
|
-
|
|
114
|
-
schedule();
|
|
185
|
+
setStatus("green", "dot", "running");
|
|
186
|
+
schedule(run);
|
|
115
187
|
} else {
|
|
116
|
-
|
|
117
|
-
sendControl(run.msg, "timeout");
|
|
118
|
-
endLoop();
|
|
188
|
+
setStatus("red", "ring", "timeout reached");
|
|
189
|
+
sendControl(run.msg, "timeout", run, "finished");
|
|
190
|
+
endLoop(run);
|
|
119
191
|
}
|
|
120
192
|
}
|
|
121
193
|
|
|
122
|
-
function stop(msg) {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
194
|
+
function stop(msg, run, reason) {
|
|
195
|
+
let state = null;
|
|
196
|
+
if (run) {
|
|
197
|
+
state = stateOf(run, "stopped");
|
|
198
|
+
endLoop(run);
|
|
199
|
+
}
|
|
200
|
+
setStatus("red", "ring", "stopped");
|
|
201
|
+
const m = controlMsg(msg, "stopped", null, null, reason);
|
|
202
|
+
if (run && run.addstate) { m.loopstate = state; }
|
|
203
|
+
node.send([null, m]);
|
|
126
204
|
}
|
|
127
205
|
|
|
128
|
-
function pause(msg) {
|
|
129
|
-
if (
|
|
130
|
-
|
|
131
|
-
clearTimer();
|
|
206
|
+
function pause(run, msg) {
|
|
207
|
+
if (run.paused) { return; }
|
|
208
|
+
clearTimers(run);
|
|
132
209
|
run.paused = true;
|
|
133
|
-
run.pausedAt = now;
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
node.
|
|
137
|
-
|
|
210
|
+
run.pausedAt = Date.now();
|
|
211
|
+
setStatus("yellow", "ring", "paused");
|
|
212
|
+
sendControl(msg, "paused", run);
|
|
213
|
+
if (node.pausetimeout > 0) {
|
|
214
|
+
const wait = toMs(node.pausetimeoutunits, node.pausetimeout);
|
|
215
|
+
const action = node.pauseaction;
|
|
216
|
+
armAt(run, "pauseTimer", Date.now() + wait, () => {
|
|
217
|
+
run.pauseTimer = null;
|
|
218
|
+
if (action === "stop") { stop(run.msg, run, "pause timeout"); } else { resume(run, run.msg, "pause timeout"); }
|
|
219
|
+
});
|
|
220
|
+
}
|
|
138
221
|
}
|
|
139
222
|
|
|
140
|
-
function resume(msg) {
|
|
141
|
-
if (!run
|
|
223
|
+
function resume(run, msg, reason) {
|
|
224
|
+
if (!run.paused) { return; }
|
|
225
|
+
if (run.pauseTimer) { clearTimeout(run.pauseTimer); run.pauseTimer = null; }
|
|
226
|
+
// The time spent paused does not count: the ticks and the timeout continue where they were left
|
|
227
|
+
const spent = Date.now() - run.pausedAt;
|
|
228
|
+
run.origin += spent;
|
|
229
|
+
run.t0 += spent;
|
|
230
|
+
run.pausedFor += spent;
|
|
142
231
|
run.paused = false;
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
schedule();
|
|
232
|
+
setStatus("green", "dot", "running");
|
|
233
|
+
sendControl(msg, "resumed", run, null, reason);
|
|
234
|
+
schedule(run);
|
|
147
235
|
}
|
|
148
236
|
|
|
149
|
-
// Validates
|
|
237
|
+
// Validates the msg.loop overrides and applies them only when all of them are valid.
|
|
238
|
+
// Returns an error text, or null when everything is fine.
|
|
150
239
|
function applyOverrides(over) {
|
|
240
|
+
const pending = [];
|
|
151
241
|
const checkUnit = (key, prop) => {
|
|
152
242
|
if (over[key] === undefined) { return null; }
|
|
153
243
|
if (!Object.prototype.hasOwnProperty.call(UNIT_MS, over[key])) {
|
|
154
244
|
node.status({ fill: "red", shape: "ring", text: `Invalid Attribute msg.loop.${key}` });
|
|
155
245
|
return `Invalid Attribute: msg.loop.${key}, allowed values are ${UNIT_LIST}`;
|
|
156
246
|
}
|
|
157
|
-
node[prop] = over[key];
|
|
247
|
+
pending.push(() => { node[prop] = over[key]; });
|
|
158
248
|
return null;
|
|
159
249
|
};
|
|
160
|
-
const checkNumber = (key, prop) => {
|
|
250
|
+
const checkNumber = (key, prop, positive) => {
|
|
161
251
|
if (over[key] === undefined) { return null; }
|
|
162
|
-
if (typeof over[key] !== "number" ||
|
|
252
|
+
if (typeof over[key] !== "number" || !isFinite(over[key])) {
|
|
163
253
|
node.status({ fill: "red", shape: "ring", text: `msg.loop.${key} must be a number` });
|
|
164
254
|
return `Invalid Attribute: msg.loop.${key}, value must be a number`;
|
|
165
255
|
}
|
|
166
|
-
|
|
256
|
+
if (positive && over[key] <= 0) {
|
|
257
|
+
node.status({ fill: "red", shape: "ring", text: `msg.loop.${key} must be greater than 0` });
|
|
258
|
+
return `Invalid Attribute: msg.loop.${key}, value must be a positive number`;
|
|
259
|
+
}
|
|
260
|
+
pending.push(() => { node[prop] = over[key]; });
|
|
167
261
|
return null;
|
|
168
262
|
};
|
|
169
|
-
|
|
170
|
-
if (
|
|
171
|
-
|
|
172
|
-
|
|
263
|
+
const checkBoolean = (key, prop) => {
|
|
264
|
+
if (over[key] === undefined) { return null; }
|
|
265
|
+
if (typeof over[key] !== "boolean") {
|
|
266
|
+
node.status({ fill: "red", shape: "ring", text: `msg.loop.${key} must be a boolean` });
|
|
267
|
+
return `Invalid Attribute: msg.loop.${key}, value must be a boolean`;
|
|
173
268
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
269
|
+
pending.push(() => { node[prop] = over[key]; });
|
|
270
|
+
return null;
|
|
271
|
+
};
|
|
272
|
+
const checkAction = () => {
|
|
273
|
+
if (over.pauseaction === undefined) { return null; }
|
|
274
|
+
if (over.pauseaction !== "resume" && over.pauseaction !== "stop") {
|
|
275
|
+
node.status({ fill: "red", shape: "ring", text: "Invalid Attribute msg.loop.pauseaction" });
|
|
276
|
+
return "Invalid Attribute: msg.loop.pauseaction, allowed values are resume and stop";
|
|
277
|
+
}
|
|
278
|
+
pending.push(() => { node.pauseaction = over.pauseaction; });
|
|
279
|
+
return null;
|
|
280
|
+
};
|
|
281
|
+
const problem = checkBoolean("totalcount", "totalcount") ||
|
|
282
|
+
checkUnit("units", "units") ||
|
|
283
|
+
checkNumber("duration", "duration", true) ||
|
|
178
284
|
checkUnit("maxtimeoutunits", "maxtimeoutunits") ||
|
|
179
285
|
checkNumber("maxtimeout", "maxtimeout") ||
|
|
180
|
-
checkNumber("maxloops", "maxloops")
|
|
286
|
+
checkNumber("maxloops", "maxloops") ||
|
|
287
|
+
checkBoolean("sendfirst", "sendfirst") ||
|
|
288
|
+
checkBoolean("loopstate", "addstate") ||
|
|
289
|
+
checkNumber("pausetimeout", "pausetimeout") ||
|
|
290
|
+
checkUnit("pausetimeoutunits", "pausetimeoutunits") ||
|
|
291
|
+
checkAction();
|
|
292
|
+
if (problem) { return problem; }
|
|
293
|
+
pending.forEach((apply) => apply());
|
|
294
|
+
return null;
|
|
181
295
|
}
|
|
182
296
|
|
|
183
297
|
function start(msg) {
|
|
184
|
-
|
|
298
|
+
const key = keyOf(msg);
|
|
299
|
+
const previous = runs.get(key);
|
|
300
|
+
if (previous) { endLoop(previous); }
|
|
301
|
+
|
|
185
302
|
const duration = toMs(node.units, node.duration);
|
|
186
303
|
const maxtimeout = toMs(node.maxtimeoutunits, node.maxtimeout);
|
|
187
304
|
const maxloops = Number(node.maxloops);
|
|
@@ -190,45 +307,109 @@ module.exports = function (RED) {
|
|
|
190
307
|
let limit = maxloops;
|
|
191
308
|
if (node.totalcount) {
|
|
192
309
|
// totalcount: maxloops is the total number of messages, first one included; -1 = unlimited.
|
|
193
|
-
limit = maxloops < 0 ? 0 : maxloops - 1;
|
|
310
|
+
limit = maxloops < 0 ? 0 : (node.sendfirst ? maxloops - 1 : maxloops);
|
|
194
311
|
if (maxloops === 0) {
|
|
195
|
-
|
|
312
|
+
setStatus("red", "ring", "max loops reached");
|
|
196
313
|
sendControl(msg, "max loops reached");
|
|
197
314
|
return;
|
|
198
315
|
}
|
|
199
|
-
if (maxloops === 1) {
|
|
316
|
+
if (maxloops === 1 && node.sendfirst) {
|
|
200
317
|
node.send([RED.util.cloneMessage(msg), null]);
|
|
201
|
-
|
|
318
|
+
setStatus("red", "ring", "max loops reached");
|
|
202
319
|
sendControl(msg, "max loops reached");
|
|
203
320
|
return;
|
|
204
321
|
}
|
|
205
322
|
}
|
|
206
323
|
|
|
207
|
-
|
|
208
|
-
run = {
|
|
324
|
+
const now = Date.now();
|
|
325
|
+
const run = {
|
|
326
|
+
key: key,
|
|
209
327
|
msg: msg,
|
|
210
328
|
duration: duration,
|
|
211
329
|
maxtimeout: maxtimeout,
|
|
212
330
|
limit: limit,
|
|
331
|
+
addstate: node.addstate,
|
|
213
332
|
count: 0,
|
|
333
|
+
sent: 0,
|
|
214
334
|
timer: null,
|
|
335
|
+
pauseTimer: null,
|
|
215
336
|
paused: false,
|
|
216
337
|
pausedAt: 0,
|
|
217
338
|
pausedFor: 0,
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
remainingTick: null,
|
|
221
|
-
remainingDeadline: null
|
|
339
|
+
origin: now, // the ticks are due at origin + n * duration
|
|
340
|
+
t0: now // start of the loop, without the time spent paused; the timeout is counted from here
|
|
222
341
|
};
|
|
223
|
-
|
|
224
|
-
|
|
342
|
+
runs.set(key, run);
|
|
343
|
+
if (node.sendfirst) {
|
|
344
|
+
run.sent = 1;
|
|
345
|
+
node.send([copyOf(run), null]);
|
|
346
|
+
}
|
|
347
|
+
setStatus("green", "dot", "running");
|
|
348
|
+
schedule(run);
|
|
225
349
|
}
|
|
226
350
|
|
|
227
|
-
|
|
228
|
-
|
|
351
|
+
// Runs that a command is meant for: the one of this topic, or all of them with msg.loop.all
|
|
352
|
+
function targets(msg, over) {
|
|
353
|
+
if (over && over.all === true) { return Array.from(runs.values()); }
|
|
354
|
+
const run = runs.get(keyOf(msg));
|
|
355
|
+
return run ? [run] : [];
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function reportStatus(msg, over) {
|
|
359
|
+
const list = targets(msg, over);
|
|
360
|
+
if (list.length === 0) {
|
|
361
|
+
const m = RED.util.cloneMessage(msg);
|
|
362
|
+
m.payload = "status";
|
|
363
|
+
m.loopstate = { state: "idle" };
|
|
364
|
+
node.send([null, m]);
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
list.forEach((run) => {
|
|
368
|
+
const m = RED.util.cloneMessage(run.msg);
|
|
369
|
+
m.payload = "status";
|
|
370
|
+
m.loopstate = stateOf(run);
|
|
371
|
+
node.send([null, m]);
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function loopOf(msg) {
|
|
376
|
+
return msg.loop !== null && typeof msg.loop === "object" ? msg.loop : undefined;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// What a message asks for: start, stop, pause, resume or status
|
|
380
|
+
function actionOf(msg) {
|
|
381
|
+
const over = loopOf(msg);
|
|
382
|
+
const command = over && typeof over.command === "string" ? over.command.toLowerCase() : null;
|
|
383
|
+
const byPayload = (word) => node.pausecontrol && isCommand(msg.payload, word);
|
|
384
|
+
|
|
385
|
+
let action = "start";
|
|
386
|
+
if (command === "pause" || byPayload("pause")) {
|
|
387
|
+
action = "pause";
|
|
388
|
+
} else if (command === "resume" || byPayload("resume")) {
|
|
389
|
+
action = "resume";
|
|
390
|
+
} else if (command === "status" || byPayload("status")) {
|
|
391
|
+
action = "status";
|
|
392
|
+
} else if (command === "stop" || isCommand(msg.payload, "stop")) {
|
|
393
|
+
action = "stop";
|
|
394
|
+
}
|
|
395
|
+
return action;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// While a loop runs the new messages are not wanted, not even their settings
|
|
399
|
+
function isIgnored(msg, action) {
|
|
400
|
+
return action === "start" && node.concurrency === "ignore" && runs.has(keyOf(msg));
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function handle(msg, done) {
|
|
404
|
+
const over = loopOf(msg);
|
|
405
|
+
const action = actionOf(msg);
|
|
229
406
|
|
|
230
|
-
|
|
231
|
-
|
|
407
|
+
if (isIgnored(msg, action)) {
|
|
408
|
+
done();
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
if (over) {
|
|
232
413
|
const problem = applyOverrides(over);
|
|
233
414
|
if (problem) {
|
|
234
415
|
node.error(problem, msg);
|
|
@@ -237,28 +418,82 @@ module.exports = function (RED) {
|
|
|
237
418
|
}
|
|
238
419
|
}
|
|
239
420
|
|
|
240
|
-
const command = over && typeof over.command === "string" ? over.command.toLowerCase() : null;
|
|
241
|
-
const byPayload = (word) => node.pausecontrol && isCommand(msg.payload, word);
|
|
242
|
-
|
|
243
421
|
try {
|
|
244
|
-
|
|
245
|
-
pause
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
422
|
+
switch (action) {
|
|
423
|
+
case "pause":
|
|
424
|
+
targets(msg, over).forEach((run) => pause(run, msg));
|
|
425
|
+
break;
|
|
426
|
+
case "resume":
|
|
427
|
+
targets(msg, over).forEach((run) => resume(run, msg));
|
|
428
|
+
break;
|
|
429
|
+
case "status":
|
|
430
|
+
reportStatus(msg, over);
|
|
431
|
+
break;
|
|
432
|
+
case "stop": {
|
|
433
|
+
const list = targets(msg, over);
|
|
434
|
+
if (list.length === 0) {
|
|
435
|
+
stop(msg, null);
|
|
436
|
+
} else {
|
|
437
|
+
list.forEach((run) => stop(msg, run));
|
|
438
|
+
}
|
|
439
|
+
break;
|
|
440
|
+
}
|
|
441
|
+
default:
|
|
442
|
+
start(msg);
|
|
252
443
|
}
|
|
253
444
|
done();
|
|
254
445
|
} catch (err) {
|
|
255
446
|
node.status({ fill: "red", shape: "ring", text: err.message });
|
|
256
447
|
done(err);
|
|
257
448
|
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// Reads the settings that are msg., flow., global. or env. values
|
|
452
|
+
function resolveTyped(msg) {
|
|
453
|
+
return Promise.all(TYPED_FIELDS.filter((field) => types[field] !== "num").map((field) => new Promise((resolve, reject) => {
|
|
454
|
+
RED.util.evaluateNodeProperty(config[field], types[field], node, msg, (err, value) => {
|
|
455
|
+
const number = Number(value);
|
|
456
|
+
if (err || value === undefined || value === null || value === "" || !isFinite(number)) {
|
|
457
|
+
node.status({ fill: "red", shape: "ring", text: `${field} must be a number` });
|
|
458
|
+
reject(new Error(`Invalid value for ${field} (${types[field]}.${config[field]}), value must be a number`));
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
if (field === "duration" && number <= 0) {
|
|
462
|
+
node.status({ fill: "red", shape: "ring", text: "duration must be greater than 0" });
|
|
463
|
+
reject(new Error(`Invalid value for ${field} (${types[field]}.${config[field]}), value must be a positive number`));
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
node[field] = field === "maxtimeout" ? Math.max(number, 0) : number;
|
|
467
|
+
resolve();
|
|
468
|
+
});
|
|
469
|
+
})));
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// Messages are handled one after the other, also when a setting has to be read from the context first
|
|
473
|
+
let queue = Promise.resolve();
|
|
474
|
+
|
|
475
|
+
node.on("input", function (msg, send, done) {
|
|
476
|
+
done = done || function (err) { if (err) { node.error(err, msg); } };
|
|
477
|
+
|
|
478
|
+
if (!hasTyped) {
|
|
479
|
+
handle(msg, done);
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
// The settings are only read for a message that starts a loop, commands and ignored messages do not need them
|
|
483
|
+
queue = queue
|
|
484
|
+
.then(() => {
|
|
485
|
+
const action = actionOf(msg);
|
|
486
|
+
return action === "start" && !isIgnored(msg, action) ? resolveTyped(msg) : null;
|
|
487
|
+
})
|
|
488
|
+
.then(() => handle(msg, done), (err) => {
|
|
489
|
+
node.error(err.message, msg);
|
|
490
|
+
done();
|
|
491
|
+
});
|
|
258
492
|
});
|
|
259
493
|
|
|
260
494
|
node.on("close", function () {
|
|
261
|
-
|
|
495
|
+
runs.forEach((run) => clearTimers(run));
|
|
496
|
+
runs.clear();
|
|
262
497
|
node.status({});
|
|
263
498
|
});
|
|
264
499
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "node-red-contrib-looptimer-advanced",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.1",
|
|
4
4
|
"description": "Sends the msg through the first output, then continues to do so in a loop, once per the duration specified, until a payload of 'stop' or 'STOP' is received. Supports override with messages!",
|
|
5
5
|
"main": "looptimer_advanced.js",
|
|
6
6
|
"scripts": {
|