1
0
mirror of https://github.com/node-red/node-red-nodes.git synced 2023-10-10 13:36:58 +02:00
node-red-nodes/function/smooth/17-smooth.js

73 lines
3.1 KiB
JavaScript
Raw Normal View History

2014-09-20 10:26:09 +02:00
module.exports = function(RED) {
"use strict";
2014-09-20 10:26:09 +02:00
function SmoothNode(n) {
RED.nodes.createNode(this, n);
this.action = n.action;
this.round = n.round || false;
if (this.round == "true") { this.round = 0; }
this.count = Number(n.count);
2017-05-24 20:45:31 +02:00
this.mult = n.mult || "single";
this.property = n.property || "payload";
var node = this;
2017-05-24 20:45:31 +02:00
var v = {};
2014-09-20 10:26:09 +02:00
this.on('input', function (msg) {
var value = RED.util.getMessageProperty(msg,node.property);
2017-05-24 20:45:31 +02:00
var top = msg.topic || "_my_default_topic";
if (this.mult === "single") { top = "a"; }
if ((v.hasOwnProperty(top) !== true) || msg.hasOwnProperty("reset")) {
v[top] = {};
v[top].a = [];
v[top].tot = 0;
v[top].tot2 = 0;
v[top].pop = 0;
v[top].old = null;
v[top].count = this.count;
}
if (value !== undefined) {
var n = Number(value);
if (!isNaN(n)) {
if ((node.action === "low") || (node.action === "high")) {
2017-05-24 20:45:31 +02:00
if (v[top].old == null) { v[top].old = n; }
v[top].old = v[top].old + (n - v[top].old) / v[top].count;
if (node.action === "low") { value = v[top].old; }
else { value = n - v[top].old; }
}
else {
2017-05-24 20:45:31 +02:00
v[top].a.push(n);
if (v[top].a.length > v[top].count) { v[top].pop = v[top].a.shift(); }
if (node.action === "max") {
value = Math.max.apply(Math, v[top].a);
}
if (node.action === "min") {
value = Math.min.apply(Math, v[top].a);
}
if (node.action === "mean") {
2017-05-24 20:45:31 +02:00
v[top].tot = v[top].tot + n - v[top].pop;
value = v[top].tot / v[top].a.length;
}
if (node.action === "sd") {
2017-05-24 20:45:31 +02:00
v[top].tot = v[top].tot + n - v[top].pop;
v[top].tot2 = v[top].tot2 + (n*n) - (v[top].pop * v[top].pop);
if (v[top].a.length > 1) {
value = Math.sqrt((v[top].a.length * v[top].tot2 - v[top].tot * v[top].tot)/(v[top].a.length * (v[top].a.length - 1)));
}
else { value = 0; }
}
}
if (node.round !== false) {
value = Math.round(value * Math.pow(10, node.round)) / Math.pow(10, node.round);
}
RED.util.setMessageProperty(msg,node.property,value);
node.send(msg);
2014-09-20 10:26:09 +02:00
}
else { node.log("Not a number: "+value); }
} // ignore msg with no payload property.
});
}
RED.nodes.registerType("smooth", SmoothNode);
2014-09-20 10:26:09 +02:00
}