Skip to content
Advertisement

Increment 2 variables in paralell Node-RED

I am trying to create a script that creates 2 variables, and increments each one of them based on a condition. The actualNetWeight is received in real-time with a MQTT connection to a server and the values are displayed in a line chart. When this value is over or equals to 0.500, I have to count that item entry as an “ok” item, and if its under 0.500, I should count it as a “under” item. The problem is that initializing these variables as I have in my code, resets them to 0 every time a new value is received, making the counters go only from 0 to 1 when the condition is met, and back to 0 when the condition is not met. So in logical terms this script works, but it only does half it’s job. I have tried many different ways of approaching this but can’t seem to get the needed results. I have also looked in Node-RED forums but there is pretty much no useful information on this tool online at all.

var ok = 0;
var under = 0;
var scartoTotale;
var actualNetWeight = msg.payload.actualNetWeight.value;
var numeroPezziTot = msg.payload.identity;

if(actualNetWeight >= 0.500)
{
    ok++;
}
else
{
    under++;
    scartoTotale += (0.500 - actualNetWeight);
}

msg.payload.ok = ok;
msg.payload.under = under;
msg.payload.scartoTotale = scartoTotale;
return msg;

The ‘msg’ is standard for Node-RED and the payload is the response I get from the server, from which I receive my data.

Answer

The important thing to remember is that the code in the function node all gets run each time a new message arrives at the input.

So the first 2 lines will always set the ok and under variables to 0.

If you want to store state between messages then you need to use what is known as the context. Details here https://nodered.org/docs/user-guide/writing-functions#storing-data

To fix your code you need to change things as follows:

var ok = context.get('ok')||0;;
var under = context.get('under')||0;;
var scartoTotale;
var actualNetWeight = msg.payload.actualNetWeight.value;
var numeroPezziTot = msg.payload.identity;

if(actualNetWeight >= 0.500)
{
    ok++;
}
else
{
    under++;
    scartoTotale += (0.500 - actualNetWeight);
}

context.set('ok', ok)
context.set('under', under)

msg.payload.ok = ok;
msg.payload.under = under;
msg.payload.scartoTotale = scartoTotale;
return msg;
Advertisement