Return data from context.get

Hello, I am newbie into the homeassistant as well as programming, but I have made some simple thing in my home automation and now I want to check if temperature sensor is not "Stucked" at same value. I try to use counting average of values inside array. But I keep failing to get the sum of values which results in reading the value as "NaN"
the code is here

[{"id":"ec5e2d42a7a7d10c","type":"group","z":"9612339af2b7a062","style":{"stroke":"#999999","stroke-opacity":"1","fill":"none","fill-opacity":"1","label":true,"label-position":"nw","color":"#a4a4a4"},"nodes":["d6c798ea44439013","3f9a57148997b2b5","4b9957a836089d27","9ceed4fa7b44f754","221b4840bbaa2af2","8a96f49405a2d131","70468ddeb3e03c94","14a4389d84d19d5d","d3342f56cda85414","2207a872a0db52f2","a767b2af1fd07b22","02f3b4631ed8305f"],"x":-6,"y":819,"w":1092,"h":488},{"id":"d6c798ea44439013","type":"api-call-service","z":"9612339af2b7a062","g":"ec5e2d42a7a7d10c","name":"notifikace na mobil","server":"35bd0ff1.ef0de","version":5,"debugenabled":false,"domain":"notify","service":"mobile_app_p30_pro_martin","areaId":[],"deviceId":[],"entityId":[],"data":"{\"message\":\"{{payload}} má asi nefunkční měření v čase {{cas}}\",\"title\":\"{{title}}\"}","dataType":"json","mergeContext":"","mustacheAltTags":false,"outputProperties":[],"queue":"all","x":890,"y":1000,"wires":[[]]},{"id":"3f9a57148997b2b5","type":"moment","z":"9612339af2b7a062","g":"ec5e2d42a7a7d10c","name":"","topic":"","input":"cas","inputType":"msg","inTz":"Europe/Prague","adjAmount":"0","adjType":"hours","adjDir":"add","format":"HH:mm:ss","locale":"C","output":"cas","outputType":"msg","outTz":"Europe/Prague","x":960,"y":940,"wires":[["d6c798ea44439013"]]},{"id":"4b9957a836089d27","type":"comment","z":"9612339af2b7a062","g":"ec5e2d42a7a7d10c","name":"Kontrola funkčnosti čidla teploty","info":"","x":150,"y":860,"wires":[]},{"id":"9ceed4fa7b44f754","type":"inject","z":"9612339af2b7a062","g":"ec5e2d42a7a7d10c","name":"12 min","props":[{"p":"cas","v":"","vt":"date"},{"p":"title","v":"Nefunkční teploměr","vt":"str"}],"repeat":"720","crontab":"","once":false,"onceDelay":0.1,"topic":"","x":120,"y":940,"wires":[["221b4840bbaa2af2"]]},{"id":"221b4840bbaa2af2","type":"change","z":"9612339af2b7a062","g":"ec5e2d42a7a7d10c","name":"teplota bojler?","rules":[{"t":"set","p":"bojler","pt":"msg","to":"tep_bojler","tot":"global"},{"t":"set","p":"pocitadlo","pt":"msg","to":"1","tot":"str"},{"t":"set","p":"payload","pt":"msg","to":"Bojler","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":300,"y":940,"wires":[["d3342f56cda85414"]]},{"id":"8a96f49405a2d131","type":"link out","z":"9612339af2b7a062","g":"ec5e2d42a7a7d10c","name":"link out 3","mode":"link","links":["4230cb89beb71088","be25093ffe136f54"],"x":755,"y":940,"wires":[]},{"id":"70468ddeb3e03c94","type":"link in","z":"9612339af2b7a062","g":"ec5e2d42a7a7d10c","name":"link in 3","links":["56bbb26dcbfb594d"],"x":815,"y":940,"wires":[["3f9a57148997b2b5"]]},{"id":"14a4389d84d19d5d","type":"inject","z":"9612339af2b7a062","g":"ec5e2d42a7a7d10c","name":"reset počítadla o půlnoci","props":[{"p":"topic","vt":"str"}],"repeat":"","crontab":"00 00 * * *","once":false,"onceDelay":0.1,"topic":"reset","x":170,"y":1000,"wires":[["221b4840bbaa2af2"]]},{"id":"d3342f56cda85414","type":"function","z":"9612339af2b7a062","g":"ec5e2d42a7a7d10c","name":"function 3","func":"var myArray = context.get(\"myArray\");\nvar maxdelka = 5;\nvar soucet = context.get(\"sum\") || 1;\nvar i = context.get(\"i\") || 1 ;\n\nif (!myArray) {\n    console.log(\"Set the array on context memory\");\n    context.set(\"myArray\", []);\n    myArray = context.get(\"myArray\");\n    \n}\n\nmyArray.push(msg.bojler);\n\nif ( i <= maxdelka ) { \n    i++;\n    soucet += myArray[i];\n    \n} \nelse {\n    i++ ;\n    myArray.splice(0 , 1);\n    soucet += myArray[i];\n}\n\nmsg.prumer = soucet / myArray.length;\ncontext.set(\"sum\", soucet);\nmsg.soucet = soucet;\n\nmsg.delka = myArray.length;\nmsg.bojler = myArray;\n\ncontext.set(\"i\", i);\nmsg.i = i;\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":460,"y":940,"wires":[["a767b2af1fd07b22","2207a872a0db52f2"]]},{"id":"2207a872a0db52f2","type":"debug","z":"9612339af2b7a062","g":"ec5e2d42a7a7d10c","name":"debug 34","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":660,"y":1020,"wires":[]},{"id":"a767b2af1fd07b22","type":"switch","z":"9612339af2b7a062","g":"ec5e2d42a7a7d10c","name":"bojler <> průměr","property":"prumer","propertyType":"msg","rules":[{"t":"eq","v":"tep_bojler","vt":"global"}],"checkall":"true","repair":false,"outputs":1,"x":640,"y":940,"wires":[["8a96f49405a2d131"]]},{"id":"02f3b4631ed8305f","type":"group","z":"9612339af2b7a062","g":"ec5e2d42a7a7d10c","style":{"stroke":"#999999","stroke-opacity":"1","fill":"none","fill-opacity":"1","label":true,"label-position":"nw","color":"#a4a4a4"},"nodes":["b73222750ed45624","951f1ae8562c96c2","678faf3c98fdeacc","4230cb89beb71088","56bbb26dcbfb594d","e6c8689b81fa0af3"],"x":314,"y":1079,"w":492,"h":202},{"id":"b73222750ed45624","type":"switch","z":"9612339af2b7a062","g":"02f3b4631ed8305f","name":"počet >5","property":"pocitadlo","propertyType":"msg","rules":[{"t":"gt","v":"5","vt":"num"}],"checkall":"true","repair":false,"outputs":1,"x":640,"y":1180,"wires":[["678faf3c98fdeacc","56bbb26dcbfb594d"]]},{"id":"951f1ae8562c96c2","type":"function","z":"9612339af2b7a062","g":"02f3b4631ed8305f","name":"Counter","func":"// Define Variable and get stored flow value\n// if there is no stored value, then the value is 0\nvar counter = flow.get(\"counter\") || 0\n\n// Check the msg.topic property\n// If the topic is equal to reset then set the counter to 0\n// else add 1 to the counter value\nif (msg.topic == \"reset\") {\n    counter = 1\n} else {\n    counter ++\n}\n\n// save the counter value in the flow variable\nflow.set(\"counter\", counter)\n\n// set msg.payload to counter value\nmsg.pocitadlo = counter\n\n// return msg Object\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":480,"y":1180,"wires":[["b73222750ed45624"]]},{"id":"678faf3c98fdeacc","type":"change","z":"9612339af2b7a062","g":"02f3b4631ed8305f","name":"reset","rules":[{"t":"set","p":"topic","pt":"msg","to":"reset","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":550,"y":1240,"wires":[["951f1ae8562c96c2"]]},{"id":"4230cb89beb71088","type":"link in","z":"9612339af2b7a062","g":"02f3b4631ed8305f","name":"link in 2","links":["8a96f49405a2d131"],"x":355,"y":1180,"wires":[["951f1ae8562c96c2"]]},{"id":"56bbb26dcbfb594d","type":"link out","z":"9612339af2b7a062","g":"02f3b4631ed8305f","name":"link out 2","mode":"link","links":["70468ddeb3e03c94"],"x":765,"y":1180,"wires":[]},{"id":"e6c8689b81fa0af3","type":"comment","z":"9612339af2b7a062","g":"02f3b4631ed8305f","name":"počítadlo do 5ti","info":"","x":540,"y":1120,"wires":[]},{"id":"35bd0ff1.ef0de","type":"server","name":"Home Assistant","version":5,"addon":true,"rejectUnauthorizedCerts":true,"ha_boolean":"y|yes|true|on|home|open","connectionDelay":true,"cacheJson":true,"heartbeat":false,"heartbeatInterval":30,"areaSelector":"friendlyName","deviceSelector":"friendlyName","entitySelector":"friendlyName","statusSeparator":"at: ","statusYear":"hidden","statusMonth":"short","statusDay":"numeric","statusHourCycle":"h23","statusTimeFormat":"h:m","enableGlobalContextStore":true}]

@vrabi-cv welcome to the forum!

It looks like you are talking about the function node labeled 'function 3'.
First line of that function is
var myArray = context.get("myArray");
why not use
var myArray = context.get("myArray") || [];
to initilize it?

Add a debug node (set to display the complete msg object) to the output of the change node 'teplota bojler?' so you can see what it is sending in.

Change the console.log to node.warn and you will see it in the debug sidebar - makes it easier to debug.

Add node.warn('something = ' + something) to display the value of variables you are using - Node, you need to change something to the name of your variable you want to see.

I would also an inject node, with msg.payload set to `"clear" and then in the function node add the following at the very beginning:

if (msg.payload == "clear") {
    context.set('i')
    context.set('myArray')
    context.set('sum')
    return
}

this will give you an easy way to clear out the context variables for testing.

Doing this you should be able to see what your code is doing and then you can figure out how to get it to do what you want it to do. :grin:

Thank you for your response. You are right my issue is inside the function 3.
The initialization of array does not work for me, so I use my code for it. Anyway I used the "clearing" and "node.warn" for debugging and the problem is "soucet += myArray[i];" this code results in NaN. If I debug "myArray[i];" while i=1, I receive NaN. If I debug "myArray[1];" I receive 23,1. Could there be some problem in the "i" variable setting?
THX Martin.

I don't know if this will help you solve the problem but remember the first element of an array is index 0. So if you have an array
cars = ["Saab", "Volvo", "BMW"];
the first element "Saab" is addressed as cars[0]

I am aware of this.
I did not write the result correctly in my previous post...these are correct results:
If I debug "myArray[i];" while i=0, I receive Undefined.
If I debug "myArray[0];" I receive 35,94 (current value of the temp).

Picture of debug after 1st run of code:
image

Picture of debug after 2nd run of code:
image

I am lost why this simple thing does not work.

Export your current flow and I’ll take a look

here is the flow:

[{"id":"d6c798ea44439013","type":"api-call-service","z":"9612339af2b7a062","name":"notifikace na mobil","server":"35bd0ff1.ef0de","version":5,"debugenabled":false,"domain":"notify","service":"mobile_app_p30_pro_martin","areaId":[],"deviceId":[],"entityId":[],"data":"{\"message\":\"Bojler má asi nefunkční měření v čase {{cas}}\",\"title\":\"{{title}}\"}","dataType":"json","mergeContext":"","mustacheAltTags":false,"outputProperties":[],"queue":"all","x":890,"y":1000,"wires":[[]]},{"id":"3f9a57148997b2b5","type":"moment","z":"9612339af2b7a062","name":"","topic":"","input":"cas","inputType":"msg","inTz":"Europe/Prague","adjAmount":"0","adjType":"hours","adjDir":"add","format":"HH:mm:ss","locale":"C","output":"cas","outputType":"msg","outTz":"Europe/Prague","x":960,"y":940,"wires":[["d6c798ea44439013"]]},{"id":"4b9957a836089d27","type":"comment","z":"9612339af2b7a062","name":"Kontrola funkčnosti čidla teploty","info":"","x":150,"y":860,"wires":[]},{"id":"9ceed4fa7b44f754","type":"inject","z":"9612339af2b7a062","name":"12 min","props":[{"p":"cas","v":"","vt":"date"},{"p":"title","v":"Nefunkční teploměr","vt":"str"}],"repeat":"720","crontab":"","once":false,"onceDelay":0.1,"topic":"","x":120,"y":940,"wires":[["221b4840bbaa2af2"]]},{"id":"221b4840bbaa2af2","type":"change","z":"9612339af2b7a062","name":"teplota bojler?","rules":[{"t":"set","p":"bojler","pt":"msg","to":"tep_bojler","tot":"global"},{"t":"set","p":"pocitadlo","pt":"msg","to":"1","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":300,"y":940,"wires":[["d3342f56cda85414"]]},{"id":"8a96f49405a2d131","type":"link out","z":"9612339af2b7a062","name":"link out 3","mode":"link","links":["4230cb89beb71088","be25093ffe136f54"],"x":755,"y":940,"wires":[]},{"id":"70468ddeb3e03c94","type":"link in","z":"9612339af2b7a062","name":"link in 3","links":["56bbb26dcbfb594d"],"x":815,"y":940,"wires":[["3f9a57148997b2b5"]]},{"id":"14a4389d84d19d5d","type":"inject","z":"9612339af2b7a062","name":"reset počítadla o půlnoci","props":[{"p":"topic","vt":"str"},{"p":"payload"}],"repeat":"","crontab":"00 00 * * *","once":false,"onceDelay":0.1,"topic":"reset","payload":"clear","payloadType":"str","x":170,"y":1000,"wires":[["221b4840bbaa2af2"]]},{"id":"d3342f56cda85414","type":"function","z":"9612339af2b7a062","name":"function 3","func":"var myArray = context.get(\"myArray\");\nvar maxdelka = 5;\nvar soucet = context.get(\"sum\") || 0;\nvar i = context.get(\"i\") || 0;\n\nif (msg.payload == \"clear\") {\n    context.set(\"i\");\n    context.set(\"myArray\");\n    context.set(\"sum\");\n    return;\n}\n\nif (!myArray) {\n    node.warn(\"Set the array on context memory\");\n    context.set(\"myArray\", []);\n    myArray = context.get(\"myArray\");\n        \n}\n\nmyArray.push(msg.bojler);\nnode.warn('i='+ i );\nnode.warn(\"myArray=\" + myArray);\n\nif ( i <= maxdelka ) { \n    i++;\n    soucet += myArray[i];\n    node.warn('myArray[i]=' + myArray[i]);\n    node.warn('myArray[0]=' + myArray[0]);\n    node.warn('myArray[1]=' + myArray[1]);\n    node.warn('myArray[2]=' + myArray[2]);\n    node.warn('soucet=' + soucet);\n} \nelse {\n    i++ ;\n    myArray.splice(0 , 1);\n    soucet += myArray[i];\n    node.warn('soucet1=' + soucet);\n}\n\nmsg.prumer = soucet / myArray.length;\ncontext.set(\"sum\", soucet);\nmsg.soucet = soucet;\nnode.warn('soucet2=' + soucet);\n\nmsg.delka = myArray.length;\nmsg.bojler = myArray;\n\ncontext.set(\"i\", i);\nmsg.i = i;\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":460,"y":940,"wires":[["a767b2af1fd07b22","2207a872a0db52f2"]]},{"id":"2207a872a0db52f2","type":"debug","z":"9612339af2b7a062","name":"debug 34","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":660,"y":1020,"wires":[]},{"id":"a767b2af1fd07b22","type":"switch","z":"9612339af2b7a062","name":"bojler <> průměr","property":"prumer","propertyType":"msg","rules":[{"t":"eq","v":"tep_bojler","vt":"global"}],"checkall":"true","repair":false,"outputs":1,"x":640,"y":940,"wires":[["8a96f49405a2d131"]]},{"id":"02f3b4631ed8305f","type":"group","z":"9612339af2b7a062","style":{"stroke":"#999999","stroke-opacity":"1","fill":"none","fill-opacity":"1","label":true,"label-position":"nw","color":"#a4a4a4"},"nodes":["b73222750ed45624","951f1ae8562c96c2","678faf3c98fdeacc","4230cb89beb71088","56bbb26dcbfb594d","e6c8689b81fa0af3"],"x":314,"y":1079,"w":492,"h":202},{"id":"b73222750ed45624","type":"switch","z":"9612339af2b7a062","g":"02f3b4631ed8305f","name":"počet >5","property":"pocitadlo","propertyType":"msg","rules":[{"t":"gt","v":"5","vt":"num"}],"checkall":"true","repair":false,"outputs":1,"x":640,"y":1180,"wires":[["678faf3c98fdeacc","56bbb26dcbfb594d"]]},{"id":"951f1ae8562c96c2","type":"function","z":"9612339af2b7a062","g":"02f3b4631ed8305f","name":"Counter","func":"// Define Variable and get stored flow value\n// if there is no stored value, then the value is 0\nvar counter = flow.get(\"counter\") || 0\n\n// Check the msg.topic property\n// If the topic is equal to reset then set the counter to 0\n// else add 1 to the counter value\nif (msg.topic == \"reset\") {\n    counter = 1\n} else {\n    counter ++\n}\n\n// save the counter value in the flow variable\nflow.set(\"counter\", counter)\n\n// set msg.payload to counter value\nmsg.pocitadlo = counter\n\n// return msg Object\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":480,"y":1180,"wires":[["b73222750ed45624"]]},{"id":"678faf3c98fdeacc","type":"change","z":"9612339af2b7a062","g":"02f3b4631ed8305f","name":"reset","rules":[{"t":"set","p":"topic","pt":"msg","to":"reset","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":550,"y":1240,"wires":[["951f1ae8562c96c2"]]},{"id":"4230cb89beb71088","type":"link in","z":"9612339af2b7a062","g":"02f3b4631ed8305f","name":"link in 2","links":["8a96f49405a2d131"],"x":355,"y":1180,"wires":[["951f1ae8562c96c2"]]},{"id":"56bbb26dcbfb594d","type":"link out","z":"9612339af2b7a062","g":"02f3b4631ed8305f","name":"link out 2","mode":"link","links":["70468ddeb3e03c94"],"x":765,"y":1180,"wires":[]},{"id":"e6c8689b81fa0af3","type":"comment","z":"9612339af2b7a062","g":"02f3b4631ed8305f","name":"počítadlo do 5ti","info":"","x":540,"y":1120,"wires":[]},{"id":"35bd0ff1.ef0de","type":"server","name":"Home Assistant","version":5,"addon":true,"rejectUnauthorizedCerts":true,"ha_boolean":"y|yes|true|on|home|open","connectionDelay":true,"cacheJson":true,"heartbeat":false,"heartbeatInterval":30,"areaSelector":"friendlyName","deviceSelector":"friendlyName","entitySelector":"friendlyName","statusSeparator":"at: ","statusYear":"hidden","statusMonth":"short","statusDay":"numeric","statusHourCycle":"h23","statusTimeFormat":"h:m","enableGlobalContextStore":true}]

Ok, your problem is two fold, the initilization of myArray and an 'if' statement.

Make a copy of your existing function node and place it elsewhere on the tab, then put this in the current function node:

var myArray = context.get("myArray")||[];

var maxdelka = 5;
var soucet = context.get("sum") || 0;
var i = context.get("i") || 0;

myArray.push(msg.bojler);

if ( i <= maxdelka ) { 
//    i++;
    soucet += myArray[i];
    i++;
 } 
else {
    i++ ;
    myArray.splice(0 , 1); 
    soucet += myArray[i];
}


msg.prumer = soucet / myArray.length;
context.set("sum", soucet);
msg.soucet = soucet;

msg.delka = myArray.length;
msg.bojler = myArray;

context.set("i", i);
msg.i = i;
context.set("myArray", myArray);

return msg;

The first line:
var myArray = context.get("myArray")||[];
sets the local variable "myArray" to the context value or an empty array.

The second to last line:
context.set("myArray", myArray);
stores the local value of "myArray" into context.

Now lets look at this code:

var i = context.get("i") || 0;     <= First time thru, 'i' will be 0

myArray.push(msg.bojler);    <= This sets myAtrray[0] to the value in msg.bojler

if ( i <= maxdelka ) {       <+ maxdelka is '5' and 'i' is 0
//    i++;                   <= this line caused the problem, 'i' becomes 1 
    soucet += myArray[i];    <= myArray[0] has a value but myArray[1] does not
    i++;                     <= so the incriment of 'i' is done here
 } 
else {
    i++ ;
    myArray.splice(0 , 1); 
    soucet += myArray[i];
}

Thank you so much for your help. I made it working, but the "soucet" variable was infinite, so I decided to count only data currently stored in the array for the average value. So finally working functions is like this:

var myArray = context.get("myArray") || [];
var maxdelka = 6;
var soucet = 0;
var i = context.get("i") || 0;

if (msg.payload == "clear") {
    context.set("i");
    context.set("myArray");
    context.set("soucet");
    return;
}

if (!myArray) {
    node.warn("Set the array on context memory");
    context.set("myArray", []);
    myArray = context.get("myArray");
        
}

myArray.push(msg.bojler);
//node.warn('i='+ i );
//node.warn("myArray=" + myArray);

if ( i <= maxdelka ) { 
    i++;
} 
else {
    i--;
    myArray.splice(0 , 1);
    i++;
}
for (var c = 0; c < myArray.length;) {
    soucet += myArray[c];
    c++;
}
c = 0;

msg.prumer = soucet / myArray.length;
msg.soucet = soucet;
msg.bojler = myArray;

context.set("i", i);
context.set("myArray", myArray);

return msg;

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