Search code examples
javascriptbooleantogglenode-red

Node-Red JavaScript Boolean toggle


I have a sound sensor which sends a mqtt message to node-red and node-red sends an new mqtt message to the module for power or trun off the light. It's the same IR code for power or turn off the light. My objective is to know when it's power on and when it's turn off. So i tried to use a simple boolean code but it doesn't work because it don't save the previous state.

I found different solution but the guys save the new state on a "cookie", the problem is, in Node-Red we don't find this kind of thing. I can't install nodes because i use a cloud hosted Node-Red(https://fred.sensetecnic.com/)

I tested many different codes, i choosed this one because it's simple to understand what i'm trying to do:

var value = true;

if (msg.payload === "sensor detection"){
    if (value === true){
        !value;
        msg.payload = "off";
    }else{
        !value;
        msg.payload = "on";
    }
}
return msg;

I post here because i really don't know how to do it, i tried many different codes and now i can't find more on google. I'm not really good and don't know all the differents tips in Javascript, so i hope someone with experience can give me interesting informations for find the solution.

Thx!


Solution

  • You need to use the context object to store state between execution of the function node:

    context.value = context.value || true;
    
    if (msg.payload === "sensor detection"){
        if (context.value === true){
            !context.value;
            msg.payload = "off";
        }else{
            !context.value;
            msg.payload = "on";
        }
    }
    return msg;