0
votes

I am testing with my new Raspberry Pi and starting with the Node-red and I have encountered an obstacle.

I try to make a loop which ends when a switch is triggered, but when it enters the while loop it does not re-read the "alarm" variable and loop infinitely.

context.data = context.data || {};
switch (msg.topic){
	case "alarma":
		context.data.alarma = msg.payload;
		msg = null;
		break;

	case "pi/13":
	    context.data.contacto = msg.payload;
	    msg = null;
	    break;
}

if(context.data.alarma === true && context.data.contacto == 1)
{

    while(context.data.alarma === true)
    {
        
        context.data.alarma = msg.payload;
        node.send({payload:true});
    }
}
return {payload:"stop"};

I have tried putting all the code in a "do - while" loop but it fails, I have also tried to put the whole switch block back into the while and the same thing. Any ideas?

I'm making an alarm system, for this I have a switch (to activate and deactivate the alarm) and a contact in a door. If the alarm is activated and the contact opens, the alarm sounds (I return true), the alarm will be disconnected if I close the contact again (that is not what I pretend) I want that only disconnect if the alarm deactivation switch is activated. If I do not turn off the switch I want it to return true so the alarm will continue to ring. I have also tried to introduce a delay so the while loop is not so fast, but still not working. What I want is to know how to actually the variable inside the loop.

Thank you!!

1

1 Answers

0
votes

That's because the variable will probably never actually change, that loop will just run so tight and never return so Node-RED will not get a chance to process any messages that would change the variable.

It will also be sending 1000's of message with payload: true

You should not need the loop at all, just return {payload: true} in the if else return {payload: 'stop'} (should that be false rather than stop?)

if(context.data.alarma === true && context.data.contacto == 1)
{
    return {payload:true});
} else {
    return {payload:"stop"};
}