I am trying to write a simple function to toggle based on receipt of of a specific payload (a button press from a zigbeetomqtt capture of a sonoff button)
if (msg.payload=="single"){
if (cur_state==0){
cur_state=1;
} else {
cur_state=0;
}
}
}
msg.payload=cur_state;
return msg;
Where / how do I declare cur_state and am I returning the updated cur_state correctly - I suspect that msg.payload=cur_state; is not the correct syntax.
Actually I just improved it by moving the msg.payload=cur_state; line back into the first if - resulting in the function passing the original payload unchanged if a switch press (a "single") was not the payload
Again the completed code for anyone interested [ is code ever complete? ]
var cur_state = context.get('cur_state')||0;
if (msg.payload=="single"){
if (cur_state===0){
context.set('cur_state', 1);
} else {
context.set('cur_state', 0);
}
msg.payload=cur_state;
}
return msg;
I believe you could get rid of the second if statement and use Context.set(‘cur_state’,Math.abs(cur_state-1)
not at my computer to make sure Math is available