Building the average of the last 5 msg and send it?

So I tried programming a function node which builds the average of the last 5 sent values and then sends it away.(to a database, because of that I save the first timestamp)
But it just wont send away anything. Did I use the context wrong? I dont know what my mistake is.
Here is the code:


var data = context.get(['count','time','spannung','strom'])||0;

var count = data[0];
var time=data[1];
var spannung=data[2];
var strom=data[3];

count+=1;
spannung += msg.payload.Spannung;
strom += msg.payload.Strom;
    
if(time==0){
    time= Date.now();
}

if(count==5){

    spannung = spannung/5;
    strom = strom/5;

    msg.payload = [{
        Spannung: spannung,
        Strom: strom,
        time: time
    },
    {
        Geraet: "WR1"
    }];
    
    context.set(['count','time','spannung','strom'],[0,0,0,0]);
    return msg;
    
} else{
    context.set(['count','time','spannung','strom'],[count,time,spannung,strom]);
    return null;
}

Does anyone of you know what my mistake is?

I think your context.get is the issue as when undefined it's default does not work.

But if you want the running average of last 5 readings i would store them in an array and limit it to 5 items, then average the array each run e.g.

[{"id":"7ec23cce.84de5c","type":"inject","z":"c791cbc0.84f648","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"Spannung\":5,\"Strom\":5}","payloadType":"json","x":140,"y":4400,"wires":[["cc19f93d.a9fd4"]]},{"id":"cc19f93d.a9fd4","type":"function","z":"c791cbc0.84f648","name":"","func":"let data = []\ndata[0] = context.get('spannung') || [];\ndata[1] = context.get('strom') || [];\n\nlet spannung=data[0];\nlet strom=data[1]\n\nspannung.unshift(msg.payload.Spannung);\nstrom.unshift(msg.payload.Strom);\n\nspannung = spannung.slice(0,5);   \nstrom = strom.slice(0,5);\n\nmsg.payload = [{\n    Spannung: spannung.reduce((a,e) => a+e)/spannung.length,\n    Strom: strom.reduce((a,e) => a+e)/strom.length,\n    time: Date.now()\n    },\n    {\n        Geraet: \"WR1\"\n    }];\n    \ncontext.set(['spannung','strom'],[spannung, strom]);\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":360,"y":4400,"wires":[["e40ac006.709d5"]]},{"id":"e40ac006.709d5","type":"debug","z":"c791cbc0.84f648","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":580,"y":4400,"wires":[]}]

The smooth node can do this for you, unless you are treating this as a learning exercise in using javascript in node-red.

1 Like

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.