Hi and welcome to the wonderful world of Node-Red
.
Its good to see you are trying, and that you have the idea of context
already.
But let's look at what is happening in the code.
=-=-=-=-
1 look at context for "active".
2 check the payload and see if it == "on"
3 set act to 1
4 save this to context "active"
5 endif
Ok. So that is ok. Could be written differently, but is neither here nor there.
6 else
7 set "act" to 0
8 save this to context "active"
9 close }
That is the end of the code to handle that message.
10 now look at "msg.topic" and see if it == "turnon" and if "act" is == 1
11 set payload to 1
12 endif
13 set payload to 0
14 close }
15 return msg
Part of the problem is you wait until the end to return the payload.
Another part is that this is processing two very different messages and there is only one "return (msg)" (msg part optional)
The first part of the code is looking at the message and setting "active" accordingly.
That should be it.
Also the way you parse the payload is complicating things.
I don't want to tell you the right and wrong way to code, but indulge me this for the first half (lines 1 - 9) though there are more lines:
var act = context.get("activate");
if (msg.payload == "on"{
context.set("activate",1);
return;
} else
if (msg.payload == "off");
context.set("activate",0);
return;
}
This is because unless you want one message to be able to affect the output.
But your implication is that there are two needed.
That looks at the incoming message and acts if the msg.payload
== "on" or == "off" and then it exits the code.
It has also set the "activate" to the state of 1
or 0
. Which persists to the next incoming message.
Now, if neither of those things happened you get to the rest of the code.....
I'll leave it there for now and see if you can get it working from what I have shown you here.
Hope it helps.