Search code examples
node.jsnode-red

how to read the state of ui-switch in node red


I have a flow using a switch from dashboard. I want to know if the switch is on or off from another node. Here is what it looks like

mqtt output node ---- MySwitch --- debug

another mqtt output node --- function        (if on) ---|-- debug
                             MySwitch state (if off) ---|

Solution

  • You have to store the state of the switch in your function node.

    Look at this example:

    [{"id":"6e716fb5.71658","type":"tab","label":"Flow 2"},{"id":"60271d4c.18ec2c","type":"ui_switch","z":"6e716fb5.71658","name":"","label":"switch","group":"167364c9.528973","order":0,"width":0,"height":0,"passthru":true,"decouple":"false","topic":"switch","style":"","onvalue":"true","onvalueType":"bool","onicon":"","oncolor":"","offvalue":"false","offvalueType":"bool","officon":"","offcolor":"","x":230,"y":60,"wires":[["dbfb1d1f.9c27a8"]]},{"id":"dbfb1d1f.9c27a8","type":"function","z":"6e716fb5.71658","name":"state","func":"var state = context.get('state') || false;\n\nif (msg.topic == 'switch') {\n    state = msg.payload;\n    context.set('state', state);\n}\n\n// put your other code here, state contains the state of the switch\n// for example:\nif (msg.payload == 'get state') {\n    return {payload: state};\n}\n\nreturn;","outputs":1,"noerr":0,"x":390,"y":120,"wires":[["4e352ab6.2e06ec"]]},{"id":"da8d8b81.67d978","type":"inject","z":"6e716fb5.71658","name":"","topic":"","payload":"get state","payloadType":"str","repeat":"","crontab":"","once":false,"x":100,"y":160,"wires":[["dbfb1d1f.9c27a8"]]},{"id":"4e352ab6.2e06ec","type":"debug","z":"6e716fb5.71658","name":"state","active":true,"console":"false","complete":"payload","x":530,"y":120,"wires":[]},{"id":"b837231b.7d88e","type":"inject","z":"6e716fb5.71658","name":"on","topic":"","payload":"true","payloadType":"bool","repeat":"","crontab":"","once":false,"x":90,"y":40,"wires":[["60271d4c.18ec2c"]]},{"id":"fcd622f5.f527e","type":"inject","z":"6e716fb5.71658","name":"off","topic":"","payload":"false","payloadType":"bool","repeat":"","crontab":"","once":false,"x":90,"y":80,"wires":[["60271d4c.18ec2c"]]},{"id":"167364c9.528973","type":"ui_group","z":"","name":"Group 1","tab":"62634de7.2b06e4","order":1,"disp":false,"width":"6"},{"id":"62634de7.2b06e4","type":"ui_tab","z":"","name":"switch test","icon":"dashboard","order":3}]
    

    example

    The code of the function-node:

    var state = context.get('state') || false;
    
    if (msg.topic == 'switch') {
        state = msg.payload;
        context.set('state', state);
    }
    
    // put your own code here, state contains the state of the switch
    // for example:
    if (msg.payload == 'get state') {
        return {payload: state};
    }
    
    return;
    

    Does it answer your question?