Toggle switch with MQTT

hello,
i am new with node-red. I use it with a MQTT bidge to a Mesh Network.
I would have a switch that make this sequence:

At the beginning i have a button with RON name
First click on the button it send the payload msg RON.
the name button and the value send must change to ROFF
a the second click ROFF is send.

I have search on the forum, but for example i don"t understand this one:

because the button don't change.

Tank's for your help.

Everything alright now? The original code posted by you was my one and it is working. :wink:

Yes, your code work fine, but my problem was a toggle button that changed after a click. I have tried some par of code. Now i have this one (in the last message i have posted only the reset part) :

But i think today, i would e better having two outputs at the end of the function. The fisrt for the msg.payload message using by another node in the flow, and the second for the button change.

Thanks a lot for your help.

[{"id":"9f4223e3.4a1cd8","type":"ui_button","z":"ff884fe7.9427b8","name":"Toggle Button","group":"eb6a632f.e9248","order":0,"width":0,"height":0,"passthru":false,"label":"{{msg.state}}","tooltip":"","color":"","bgcolor":"{{msg.background}}","icon":"","payload":"true","payloadType":"bool","topic":"","x":680,"y":440,"wires":[["27e101fd.2d8fae"]]},{"id":"d82852bc.c0dd3","type":"inject","z":"ff884fe7.9427b8","name":"","topic":"","payload":"reset","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":640,"y":380,"wires":[["27e101fd.2d8fae"]]},{"id":"27e101fd.2d8fae","type":"function","z":"ff884fe7.9427b8","name":"Function","func":"\nvar state=context.get(\"state\") || \"OFF\";\n\nvar color = '';\nif (msg.payload===\"reset\") {\n    state=\"OFF\"\n    color = 'red';\n    txt = \"OFF\"\n    msg.state=\"ON\";\n}\nelse{\n\nif ((msg.payload===true) && (state==\"OFF\")) {\n    state=!state;\n    context.set(\"state\",\"ON\") ;\n    msg.payload=\"MSG_ON\";\n    color = \"green\";\n    txt = \"ON\"\n    msg.state=\"OFF\";\n\n} \nelse {\n    msg.payload=\"MSG_OFF\";\n    context.set(\"state\",\"OFF\") ;\n    color = 'red';\n    txt = \"OFF\"\n    msg.state=\"ON\";\n}\n}\n\n node.status({\n    \tfill : color,\n    \tshape : 'dot',\n    \ttext : txt\n });\nnode.send(msg);\nmsg.background=color;\n\n\n\nreturn msg;\n","outputs":1,"noerr":0,"x":920,"y":440,"wires":[["9f4223e3.4a1cd8","9f28e900.e94d78"]]},{"id":"eb6a632f.e9248","type":"ui_group","z":"","name":"Carte 1 V2","tab":"62c54554.67f834","disp":true,"width":"6","collapse":true},{"id":"62c54554.67f834","type":"ui_tab","z":"","name":"Home","icon":"dashboard","disabled":false,"hidden":false}]

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.