-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathaverage.js
More file actions
53 lines (41 loc) · 1.46 KB
/
average.js
File metadata and controls
53 lines (41 loc) · 1.46 KB
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
module.exports = function(RED) {
'use strict';
function average(config) {
RED.nodes.createNode(this, config);
let node = this;
this.topic = config.topic;
this.topics = {};
this.on('input', (msg) => {
if (msg.hasOwnProperty('payload')) {
let input = Number(msg.payload);
// handle reset
if (msg.hasOwnProperty('reset') && msg.reset) {
node.topics = {};
msg.payload = 0;
node.send(msg);
}
// handle input
else if (!isNaN(input) && isFinite(input)) {
node.topics[msg.topic.toString()] = input;
let amount = 0;
let sum = Object.keys(node.topics).reduce((a, b) => {
++amount;
return a + node.topics[b];
}, 0);
msg.payload = sum / amount;
msg.topics_count = amount;
// overwrite topic if configured
if (node.topic) {
msg.topic = node.topic;
}
node.send(msg);
}
// everything else
else {
node.log(`Not a number: ${msg.payload}`);
}
}
});
}
RED.nodes.registerType('average', average);
};