# Two way switch infinite loop

**URL:** <https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115>\
**Category:** General\
**Tags:** function-node, mqtt\
**Created:** [30 August 2022 09:24 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115 "2022-08-30T09:24:18Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![petertmooney](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/petertmooney/32/67093_2.png) [@petertmooney](https://discourse.nodered.org/u/petertmooney)\
**Post date:** [30 August 2022 09:24 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/1 "2022-08-30T09:24:18Z")

</div>

Hi all  
I am very new to node red and home automation. I have a switch at the bottom of the stairs and one also at the top. There is also a lamp at top and bottom of stairs, ie. hall/landing.

I have been trying to create a setup whereby when one of the switches is turned on, both lamps come on and the other switch changes to match the state. Also, If one of the lamps is turned on from HomeKit or home assistant, switches should mirror this..

I have managed to achieve what I wanted to do, apart from once it is triggered, a loop begins and switches and lamps rapidly cycle on/off.

I know I am doing something stupid, but being new to it, I cannot see where.

Could anybody please look at this and point me in the right direction?

```auto
[
    {
        "id": "13a1a7ceb6a497a4",
        "type": "group",
        "z": "2a17042efaa3b23d",
        "style": {
            "stroke": "#999999",
            "stroke-opacity": "1",
            "fill": "none",
            "fill-opacity": "1",
            "label": true,
            "label-position": "nw",
            "color": "#a4a4a4"
        },
        "nodes": [
            "7ff3a66a.bd9c08",
            "52e0bc3b.617904",
            "acbfa624.3650d8",
            "bb484857.94bc",
            "a0834568.7e447",
            "406daced.472844",
            "a33d117e.961728",
            "d2d365921bab591a",
            "e29e54f8eb805979"
        ],
        "x": 54,
        "y": 139,
        "w": 972,
        "h": 242
    },
    {
        "id": "7ff3a66a.bd9c08",
        "type": "mqtt in",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "topic": "zigbee2mqtt/Stairs Switch/state_l1",
        "qos": "2",
        "datatype": "auto-detect",
        "broker": "12dd1610.da9e4a",
        "nl": false,
        "rap": false,
        "rh": "0",
        "inputs": 0,
        "x": 220,
        "y": 220,
        "wires": [
            [
                "bb484857.94bc"
            ]
        ]
    },
    {
        "id": "52e0bc3b.617904",
        "type": "mqtt in",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "topic": "zigbee2mqtt/Landing Switch/state_l3",
        "qos": "2",
        "datatype": "auto-detect",
        "broker": "12dd1610.da9e4a",
        "nl": false,
        "rap": false,
        "rh": "0",
        "inputs": 0,
        "x": 230,
        "y": 280,
        "wires": [
            []
        ]
    },
    {
        "id": "acbfa624.3650d8",
        "type": "mqtt out",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "topic": "zigbee2mqtt/Stairs Switch/l1/set",
        "qos": "",
        "retain": "",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "12dd1610.da9e4a",
        "x": 850,
        "y": 340,
        "wires": []
    },
    {
        "id": "bb484857.94bc",
        "type": "function",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "2way stairs lights",
        "func": "var newMsg = { topic: \"zigbee2mqtt/Stairs Switch/state_l1\"}; \nvar hallstairs=flow.get('hallstairs') || 0;\nvar newMsg = { topic: \"zigbee2mqtt/Landing Switch/state_l3\" };\nvar landingstairs = flow.get('landingstairs') || 0;\nvar newMsg = { topic: \"zigbee2mqtt/Stairs/state\" };\nvar stairs = flow.get('stairs') || 0;\n\n//if (msg.topic===\"\"zigbee2mqtt/Landing Switch/state_l3\") {\nif (landingstairs === 0) {\n if (msg.payload === \"ON\") {\n newMsg.payload = \"ON\";\n landingstairs = 1\n flow.set('landingstairs', landingstairs);\n return newMsg;\n }\n}\nelse {\n if (msg.payload === \"OFF\") {\n newMsg.payload = \"OFF\";\n landingstairs = 0;\n flow.set('landingstairs', landingstairs);\n return newMsg;\n }\n}\n//if (msg.topic===\"zigbee2mqtt/Stairs Switch/state_l1\") {\nif (hallstairs === 0) {\n if (msg.payload === \"ON\") {\n newMsg.payload = \"ON\";\n hallstairs = 1\n flow.set('hallstairs', hallstairs);\n return newMsg;\n }\n}\nelse {\n if (msg.payload === \"OFF\") {\n newMsg.payload = \"OFF\";\n hallstairs = 0;\n flow.set('hallstairs', hallstairs);\n return newMsg;\n }\n}\n//if (msg.topic===\"zigbee2mqtt/Stairs/state\") {\nif (stairs === 0) {\n if (msg.payload === \"ON\") {\n newMsg.payload = \"ON\";\n stairs = 1\n flow.set('stairs', stairs);\n return newMsg;\n }\n}\nelse {\n if (msg.payload === \"OFF\") {\n newMsg.payload = \"OFF\";\n stairs = 0;\n flow.set('stairs', stairs);\n return newMsg;\n }\n}\n//}",
        "outputs": 2,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 510,
        "y": 320,
        "wires": [
            [
                "a0834568.7e447",
                "d2d365921bab591a",
                "acbfa624.3650d8"
            ],
            []
        ],
        "inputLabels": [
            "House/LightLobbyA/stat/POWER"
        ]
    },
    {
        "id": "a0834568.7e447",
        "type": "mqtt out",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "topic": "zigbee2mqtt/Stairs/set",
        "qos": "",
        "retain": "false",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "12dd1610.da9e4a",
        "x": 820,
        "y": 220,
        "wires": []
    },
    {
        "id": "406daced.472844",
        "type": "inject",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "props": [
            {
                "p": "payload",
                "v": "ON",
                "vt": "str"
            },
            {
                "p": "topic",
                "v": "",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "ON",
        "payloadType": "str",
        "x": 550,
        "y": 180,
        "wires": [
            [
                "bb484857.94bc"
            ]
        ],
        "outputLabels": [
            "House/LightLobbyA/stat/POWER"
        ]
    },
    {
        "id": "a33d117e.961728",
        "type": "inject",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "props": [
            {
                "p": "payload",
                "v": "OFF",
                "vt": "str"
            },
            {
                "p": "topic",
                "v": "",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "OFF",
        "payloadType": "str",
        "x": 550,
        "y": 220,
        "wires": [
            [
                "bb484857.94bc"
            ]
        ],
        "outputLabels": [
            "House/LightLobbyA/stat/POWER"
        ]
    },
    {
        "id": "d2d365921bab591a",
        "type": "mqtt out",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "topic": "zigbee2mqtt/Landing Switch/l3/set",
        "qos": "",
        "retain": "",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "1071c397f831a1ed",
        "x": 860,
        "y": 280,
        "wires": []
    },
    {
        "id": "e29e54f8eb805979",
        "type": "mqtt in",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "topic": "zigbee2mqtt/Stairs/state",
        "qos": "2",
        "datatype": "auto-detect",
        "broker": "1071c397f831a1ed",
        "nl": false,
        "rap": true,
        "rh": 0,
        "inputs": 0,
        "x": 190,
        "y": 340,
        "wires": [
            [
                "bb484857.94bc"
            ]
        ]
    },
    {
        "id": "12dd1610.da9e4a",
        "type": "mqtt-broker",
        "name": "",
        "broker": "localhost",
        "port": "1883",
        "clientid": "",
        "autoConnect": true,
        "usetls": false,
        "protocolVersion": "4",
        "keepalive": "60",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthRetain": "false",
        "birthPayload": "",
        "birthMsg": {},
        "closeTopic": "",
        "closeQos": "0",
        "closeRetain": "false",
        "closePayload": "",
        "closeMsg": {},
        "willTopic": "",
        "willQos": "0",
        "willRetain": "false",
        "willPayload": "",
        "willMsg": {},
        "userProps": "",
        "sessionExpiry": ""
    },
    {
        "id": "1071c397f831a1ed",
        "type": "mqtt-broker",
        "name": "",
        "broker": "localhost",
        "port": "1883",
        "clientid": "",
        "autoConnect": true,
        "usetls": false,
        "protocolVersion": "4",
        "keepalive": "60",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthRetain": "false",
        "birthPayload": "",
        "birthMsg": {},
        "closeTopic": "",
        "closeQos": "0",
        "closeRetain": "false",
        "closePayload": "",
        "closeMsg": {},
        "willTopic": "",
        "willQos": "0",
        "willRetain": "false",
        "willPayload": "",
        "willMsg": {},
        "userProps": "",
        "sessionExpiry": ""
    }
]

```

---

<div class="post-metadata">

**Author:** ![Paul-Reed](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/paul-reed/32/66906_2.png) [@Paul-Reed](https://discourse.nodered.org/u/Paul-Reed)\
**Post date:** [30 August 2022 09:47 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/2 "2022-08-30T09:47:20Z")

</div>

Hi Peter, the flow that you posted cannot be imported for others to test because it has not been formatted correctly.  
Any code or flows posted in the forum **must** follow these guidelines;

> [@How to share code or flow json](https://discourse.nodered.org/t/how-to-share-code-or-flow-json/506):
>
> To share code samples or flow json in this forum, you need to take care to format it properly so that it is displayed correctly. The easiest way to do that is to click the 'Preformatted Text' button in the toolbar: [image] Then paste in your code or flow json. You should end up with three back-tick characters - ``` - on their own line before and after the code. On standard US English keyboards, this is on the same key as the ~ character. Using the backticks will ens…

Please read the link, then edit your post above using the pencil icon at the bottom of your post.

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [30 August 2022 10:00 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/3 "2022-08-30T10:00:48Z")

</div>

I haven't looked at the flow, but if you are using dashboard switch nodes then set them to Not pass messages through, and select Show State of Input. That way the switch shows the state that is passed in to it, and does not pass the message on, so no loop.

---

<div class="post-metadata">

**Author:** ![petertmooney](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/petertmooney/32/67093_2.png) [@petertmooney](https://discourse.nodered.org/u/petertmooney)\
**Post date:** [30 August 2022 12:24 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/4 "2022-08-30T12:24:28Z")

</div>

Thank you.

I think that’s it edited correctly now?

---

<div class="post-metadata">

**Author:** ![petertmooney](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/petertmooney/32/67093_2.png) [@petertmooney](https://discourse.nodered.org/u/petertmooney)\
**Post date:** [30 August 2022 12:25 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/5 "2022-08-30T12:25:07Z")

</div>

I have the switches as MQTT in and MQTT out.

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [30 August 2022 13:02 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/6 "2022-08-30T13:02:56Z")

</div>

OK, now I can import the flow I see you are not using dashboard switches.

The technique to debug this is to sprinkle `node.warn()` statements throughout the code. The output from those will go into the node red log. Start the loop going and then stop node-red. You can then look back through the log and work out exactly what is happening so you can see how to fix it.

---

<div class="post-metadata">

**Author:** ![petertmooney](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/petertmooney/32/67093_2.png) [@petertmooney](https://discourse.nodered.org/u/petertmooney)\
**Post date:** [30 August 2022 13:06 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/7 "2022-08-30T13:06:13Z")

</div>

> [@Colin](#):
>
> `node.warn()`

that would go in the function section?

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [30 August 2022 13:12 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/8 "2022-08-30T13:12:25Z")

</div>

`node.warn("some string")` outputs the text to the log, so you can use them to show the flow through the function by inserting them at appropriate points. So you might add the line  
`node.warn("Point A")`  
to indicate a particular point, or you might output the value of a variable at that point

```auto
node.warn(`Point C. msg.payload is ${msg.payload}`)

```

which will include the current msg.payload value in the text.

---

<div class="post-metadata">

**Author:** ![petertmooney](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/petertmooney/32/67093_2.png) [@petertmooney](https://discourse.nodered.org/u/petertmooney)\
**Post date:** [30 August 2022 13:19 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/9 "2022-08-30T13:19:07Z")

</div>

I just cannot figure it out. I redeployed it and had all going well there. then randomly same thing happens for no apparent reason. It will just start sporadically switching bits on and off.

This is the current state including the motion sensors for late night.

```auto
[
    {
        "id": "13a1a7ceb6a497a4",
        "type": "group",
        "z": "2a17042efaa3b23d",
        "style": {
            "stroke": "#999999",
            "stroke-opacity": "1",
            "fill": "none",
            "fill-opacity": "1",
            "label": true,
            "label-position": "nw",
            "color": "#a4a4a4"
        },
        "nodes": [
            "7ff3a66a.bd9c08",
            "52e0bc3b.617904",
            "acbfa624.3650d8",
            "bb484857.94bc",
            "a0834568.7e447",
            "406daced.472844",
            "a33d117e.961728",
            "d2d365921bab591a",
            "e29e54f8eb805979",
            "a8fba4fcb78b6fb1",
            "11c7e80d.388958",
            "bcf61976eca52521",
            "20f6aead.8b5d52"
        ],
        "x": 14,
        "y": 99,
        "w": 1072,
        "h": 262
    },
    {
        "id": "7ff3a66a.bd9c08",
        "type": "mqtt in",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "topic": "zigbee2mqtt/Stairs Switch/state_l1",
        "qos": "2",
        "datatype": "auto-detect",
        "broker": "12dd1610.da9e4a",
        "nl": false,
        "rap": false,
        "rh": "0",
        "inputs": 0,
        "x": 340,
        "y": 220,
        "wires": [
            [
                "bb484857.94bc"
            ]
        ]
    },
    {
        "id": "52e0bc3b.617904",
        "type": "mqtt in",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "topic": "zigbee2mqtt/Landing Switch/state_l3",
        "qos": "2",
        "datatype": "auto-detect",
        "broker": "12dd1610.da9e4a",
        "nl": false,
        "rap": false,
        "rh": "0",
        "inputs": 0,
        "x": 330,
        "y": 280,
        "wires": [
            [
                "bb484857.94bc"
            ]
        ]
    },
    {
        "id": "acbfa624.3650d8",
        "type": "mqtt out",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "topic": "zigbee2mqtt/Stairs Switch/l1/set",
        "qos": "",
        "retain": "false",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "12dd1610.da9e4a",
        "x": 910,
        "y": 320,
        "wires": []
    },
    {
        "id": "bb484857.94bc",
        "type": "function",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "2way stairs lights",
        "func": "var newMsg = { topic: \"zigbee2mqtt/Stairs Switch/state_l1\"}; \nvar hallstairs=flow.get('hallstairs') || 0;\nvar newMsg = { topic: \"zigbee2mqtt/Landing Switch/state_l3\" };\nvar landingstairs = flow.get('landingstairs') || 0;\nvar newMsg = { topic: \"zigbee2mqtt/Stairs/state\" };\nvar stairs = flow.get('stairs') || 0;\n\n//if (msg.topic===\"\"zigbee2mqtt/Landing Switch/state_l3\") {\nif (landingstairs === 0) {\n if (msg.payload === \"ON\") {\n newMsg.payload = \"ON\";\n landingstairs = 1\n flow.set('landingstairs', landingstairs);\n return newMsg;\n }\n}\nelse {\n if (msg.payload === \"OFF\") {\n newMsg.payload = \"OFF\";\n landingstairs = 0;\n flow.set('landingstairs', landingstairs);\n return newMsg;\n }\n}\n//if (msg.topic===\"zigbee2mqtt/Stairs Switch/state_l1\") {\nif (hallstairs === 0) {\n if (msg.payload === \"ON\") {\n newMsg.payload = \"ON\";\n hallstairs = 1\n flow.set('hallstairs', hallstairs);\n return newMsg;\n }\n}\nelse {\n if (msg.payload === \"OFF\") {\n newMsg.payload = \"OFF\";\n hallstairs = 0;\n flow.set('hallstairs', hallstairs);\n return newMsg;\n }\n}\n//if (msg.topic===\"zigbee2mqtt/Stairs/state\") {\nif (stairs === 0) {\n if (msg.payload === \"ON\") {\n newMsg.payload = \"ON\";\n stairs = 1\n flow.set('stairs', stairs);\n return newMsg;\n }\n}\nelse {\n if (msg.payload === \"OFF\") {\n newMsg.payload = \"OFF\";\n stairs = 0;\n flow.set('stairs', stairs);\n return newMsg;\n }\n}\n//}",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 630,
        "y": 240,
        "wires": [
            [
                "a0834568.7e447",
                "d2d365921bab591a",
                "acbfa624.3650d8",
                "a8fba4fcb78b6fb1"
            ]
        ],
        "inputLabels": [
            "House/LightLobbyA/stat/POWER"
        ]
    },
    {
        "id": "a0834568.7e447",
        "type": "mqtt out",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "topic": "zigbee2mqtt/Stairs/set",
        "qos": "",
        "retain": "false",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "12dd1610.da9e4a",
        "x": 860,
        "y": 200,
        "wires": []
    },
    {
        "id": "406daced.472844",
        "type": "inject",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "ON",
        "payloadType": "str",
        "x": 110,
        "y": 240,
        "wires": [
            [
                "bb484857.94bc"
            ]
        ],
        "outputLabels": [
            "House/LightLobbyA/stat/POWER"
        ]
    },
    {
        "id": "a33d117e.961728",
        "type": "inject",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "props": [
            {
                "p": "payload",
                "v": "OFF",
                "vt": "str"
            },
            {
                "p": "topic",
                "v": "",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "OFF",
        "payloadType": "str",
        "x": 110,
        "y": 300,
        "wires": [
            [
                "bb484857.94bc"
            ]
        ],
        "outputLabels": [
            "House/LightLobbyA/stat/POWER"
        ]
    },
    {
        "id": "d2d365921bab591a",
        "type": "mqtt out",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "topic": "zigbee2mqtt/Landing Switch/l3/set",
        "qos": "",
        "retain": "false",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "1071c397f831a1ed",
        "x": 920,
        "y": 260,
        "wires": []
    },
    {
        "id": "e29e54f8eb805979",
        "type": "mqtt in",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "topic": "zigbee2mqtt/Stairs/state",
        "qos": "2",
        "datatype": "auto-detect",
        "broker": "1071c397f831a1ed",
        "nl": false,
        "rap": true,
        "rh": 0,
        "inputs": 0,
        "x": 350,
        "y": 320,
        "wires": [
            [
                "bb484857.94bc"
            ]
        ]
    },
    {
        "id": "a8fba4fcb78b6fb1",
        "type": "debug",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "debug 1",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "statusVal": "",
        "statusType": "auto",
        "x": 820,
        "y": 160,
        "wires": []
    },
    {
        "id": "11c7e80d.388958",
        "type": "trigger",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "",
        "op1": "{\"service\": \"turn_on\"}",
        "op2": "{\"service\": \"turn_off\"}",
        "op1type": "json",
        "op2type": "json",
        "duration": "5",
        "extend": true,
        "overrideDelay": false,
        "units": "min",
        "reset": "",
        "bytopic": "all",
        "topic": "topic",
        "outputs": 1,
        "x": 470,
        "y": 140,
        "wires": [
            [
                "bb484857.94bc"
            ]
        ]
    },
    {
        "id": "bcf61976eca52521",
        "type": "time-range-switch",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "late night",
        "lat": "",
        "lon": "",
        "startTime": "23:00",
        "endTime": "08:30",
        "startOffset": "0",
        "endOffset": "0",
        "x": 300,
        "y": 160,
        "wires": [
            [
                "11c7e80d.388958"
            ],
            []
        ]
    },
    {
        "id": "20f6aead.8b5d52",
        "type": "server-state-changed",
        "z": "2a17042efaa3b23d",
        "g": "13a1a7ceb6a497a4",
        "name": "hall motion",
        "server": "b4b6ee5a.46dfd",
        "version": 4,
        "exposeToHomeAssistant": false,
        "haConfig": [
            {
                "property": "name",
                "value": ""
            },
            {
                "property": "icon",
                "value": ""
            }
        ],
        "entityidfilter": [
            "binary_sensor.hall_motion_occupancy",
            "binary_sensor.landing_motion_occupancy"
        ],
        "entityidfiltertype": "list",
        "outputinitially": false,
        "state_type": "str",
        "haltifstate": "",
        "halt_if_type": "str",
        "halt_if_compare": "is",
        "outputs": 1,
        "output_only_on_state_change": true,
        "for": "0",
        "forType": "num",
        "forUnits": "minutes",
        "ignorePrevStateNull": false,
        "ignorePrevStateUnknown": false,
        "ignorePrevStateUnavailable": false,
        "ignoreCurrentStateUnknown": false,
        "ignoreCurrentStateUnavailable": false,
        "outputProperties": [
            {
                "property": "payload",
                "propertyType": "msg",
                "value": "",
                "valueType": "entityState"
            },
            {
                "property": "data",
                "propertyType": "msg",
                "value": "",
                "valueType": "eventData"
            },
            {
                "property": "topic",
                "propertyType": "msg",
                "value": "",
                "valueType": "triggerId"
            }
        ],
        "x": 140,
        "y": 160,
        "wires": [
            [
                "bcf61976eca52521"
            ]
        ]
    },
    {
        "id": "12dd1610.da9e4a",
        "type": "mqtt-broker",
        "name": "",
        "broker": "localhost",
        "port": "1883",
        "clientid": "",
        "autoConnect": true,
        "usetls": false,
        "protocolVersion": "4",
        "keepalive": "60",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthRetain": "false",
        "birthPayload": "",
        "birthMsg": {},
        "closeTopic": "",
        "closeQos": "0",
        "closeRetain": "false",
        "closePayload": "",
        "closeMsg": {},
        "willTopic": "",
        "willQos": "0",
        "willRetain": "false",
        "willPayload": "",
        "willMsg": {},
        "userProps": "",
        "sessionExpiry": ""
    },
    {
        "id": "1071c397f831a1ed",
        "type": "mqtt-broker",
        "name": "",
        "broker": "localhost",
        "port": "1883",
        "clientid": "",
        "autoConnect": true,
        "usetls": false,
        "protocolVersion": "4",
        "keepalive": "60",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthRetain": "false",
        "birthPayload": "",
        "birthMsg": {},
        "closeTopic": "",
        "closeQos": "0",
        "closeRetain": "false",
        "closePayload": "",
        "closeMsg": {},
        "willTopic": "",
        "willQos": "0",
        "willRetain": "false",
        "willPayload": "",
        "willMsg": {},
        "userProps": "",
        "sessionExpiry": ""
    },
    {
        "id": "b4b6ee5a.46dfd",
        "type": "server",
        "name": "Home Assistant",
        "version": 4,
        "addon": true,
        "rejectUnauthorizedCerts": true,
        "ha_boolean": "y|yes|true|on|home|open",
        "connectionDelay": true,
        "cacheJson": true,
        "heartbeat": true,
        "heartbeatInterval": "30",
        "areaSelector": "friendlyName",
        "deviceSelector": "friendlyName",
        "entitySelector": "friendlyName",
        "statusSeparator": "at: ",
        "statusYear": "2-digit",
        "statusMonth": "short",
        "statusDay": "numeric",
        "statusHourCycle": "h23",
        "statusTimeFormat": "h:m"
    }
]

```

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [30 August 2022 13:32 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/10 "2022-08-30T13:32:46Z")

</div>

> [@petertmooney](#):
>
> I just cannot figure it out. I redeployed it and had all going well there. then randomly same thing happens for no apparent reason.

The reason will become apparent when you add the diagnostics and look at where it started to go wrong. Consider, for example what would happen if two of the switched were changed manually at almost the same time, so you have two messages coming in one after the other, so the first one will send off the new states to MQTT, but then the function will interpret the second message that is already waiting to be actioned. At that moment, the flow context variables will not represent the state when the second switch was activated.

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [30 August 2022 14:57 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/11 "2022-08-30T14:57:22Z")

</div>

When you get a message coming in from MQTT saying that a switch has changed, have you any way of knowing whether the change is as a result of your code changing the switch via MQTT or whether it is an external agency changing the switch?

---

<div class="post-metadata">

**Author:** ![petertmooney](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/petertmooney/32/67093_2.png) [@petertmooney](https://discourse.nodered.org/u/petertmooney)\
**Post date:** [30 August 2022 22:17 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/12 "2022-08-30T22:17:46Z")

</div>

no, its just an mutt state input. so the same message is received regardless of the switch being physically initiated, or via HomeKit/homeassistant etc

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [31 August 2022 08:35 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/13 "2022-08-31T08:35:30Z")

</div>

That makes it very tricky to avoid such problems. I suspect you will be able to trip it into the loop condition by switching both switches at approximately the same time.  
One possibility might be to feed the three MQTT values into a Join node in key/value pairs mode, sending after every value comes in.  
I know logically what to do next but I am not sure the best way to code it. I am [starting a new thread](https://discourse.nodered.org/t/can-the-delay-node-rate-limit-but-pass-first-message-immediately-and-always-pass-on-the-latest-message/67170) to ask for help with the best way to do it.

---

<div class="post-metadata">

**Author:** ![Trying\_to\_learn](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/trying_to_learn/32/28400_2.png) [@Trying\_to\_learn](https://discourse.nodered.org/u/Trying_to_learn)\
**Post date:** [31 August 2022 09:25 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/14 "2022-08-31T09:25:06Z")

</div>

But what you could do is add extra _attributes_ to the message telling you _who_ sent it.

So if it is the _button_ (switch/what ever) it would be more like:

`msg.payload{"switch":"x","who":"switch 1"}`

Yes, you will have to add a bit to _decode_ the newer style message, but it may help you.  
Or not. 🙂

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [31 August 2022 09:44 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/15 "2022-08-31T09:44:00Z")

</div>

The messages are coming from a Shelley switch.

---

<div class="post-metadata">

**Author:** ![Trying\_to\_learn](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/trying_to_learn/32/28400_2.png) [@Trying\_to\_learn](https://discourse.nodered.org/u/Trying_to_learn)\
**Post date:** [31 August 2022 09:44 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/16 "2022-08-31T09:44:42Z")

</div>

Oh.

Sorry.

I guess that makes it difficult. ☹

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [31 August 2022 12:54 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/17 "2022-08-31T12:54:36Z")

</div>

OK, I have a solution, at least in outline. As I suggested earlier, feed the three MQTT values into a Join node in key/value pairs mode, sending after every value comes in. Then feed that into this flow (from the thread I linked to earlier), which will ensure that only one message gets through every 0.5 seconds, which will prevent the loop from ensuing.

![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/4/3/4356e9fb50699cd5d6e40cf2022b1face2e12eee.png)

```auto
[{"id":"8c004dc7912dc3ac","type":"trigger","z":"bdd7be38.d3b55","name":"","op1":"","op2":"","op1type":"pay","op2type":"payl","duration":"0.5","extend":false,"overrideDelay":false,"units":"s","reset":"","bytopic":"all","topic":"topic","outputs":1,"x":430,"y":3920,"wires":[["f2d6fb1495637cd9"]]},{"id":"f2d6fb1495637cd9","type":"rbe","z":"bdd7be38.d3b55","name":"Block repeated messages","func":"rbe","gap":"","start":"","inout":"out","septopics":false,"property":"payload","topi":"topic","x":665,"y":3920,"wires":[[]]}]

```

Then in your function you will receive a message containing all three inputs. Amend the logic there to remember the previous states of the inputs and work out what to do with the new states. You will have to cope with the initial condition which will be that the message may not yet contain values for all inputs. If the mqtt topics for the inputs are Retained (so you are guaranteed to get values immediately on startup) then change the Join node to wait for three messages (but keep the And every message thereafter), and you will know that your function will always have all three states.

---

<div class="post-metadata">

**Author:** ![petertmooney](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/petertmooney/32/67093_2.png) [@petertmooney](https://discourse.nodered.org/u/petertmooney)\
**Post date:** [31 August 2022 21:02 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/18 "2022-08-31T21:02:03Z")

</div>

This seems to be working. awesome!

---

<div class="post-metadata">

**Author:** ![petertmooney](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/petertmooney/32/67093_2.png) [@petertmooney](https://discourse.nodered.org/u/petertmooney)\
**Post date:** [2 September 2022 10:44 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/19 "2022-09-02T10:44:27Z")

</div>

I have this all working well now, apart from one item. The landing lamp.  
The rest come through Matt, but the landing lamp is wifi and as a home assitant device entity.  
when I add it to the function like this:  
var newMsg = { topic: "Landing Lamp"};  
var landinglamp = flow.get("light.landing.lamp") || 0;  
it doesn’t seem to send messages to the function. What stupid thing am I doing wrong?

````auto
var newMsg = { topic: "zigbee2mqtt/Stairs Switch/state_l2"}; 
var halllamps=flow.get('halllamps') || 0;
var newMsg = { topic: "zigbee2mqtt/Landing Switch/state_l2" };
var landinglamps = flow.get('landinglamps') || 0;
var newMsg = { topic: "Landing Lamp"};
var landinglamp = flow.get("light.landing.lamp") || 0;

//if (msg.topic===""zigbee2mqtt/Landing Switch/state_l2") {
if (landinglamps === 0) {
    if (msg.payload === "ON") {
        newMsg.payload = "ON";
        landinglamps = 1
        flow.set('landinglamps', landinglamps);
        return newMsg;
    }
}```
````

---

<div class="post-metadata">

**Author:** ![Sean-McG](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/sean-mcg/32/54677_2.png) [@Sean-McG](https://discourse.nodered.org/u/Sean-McG)\
**Post date:** [2 September 2022 12:01 UTC](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115/20 "2022-09-02T12:01:18Z")

</div>

> [@petertmooney](#):
>
> ```auto
> var newMsg = { topic: "zigbee2mqtt/Stairs Switch/state_l2"}; 
> var halllamps=flow.get('halllamps') || 0;
> var newMsg = { topic: "zigbee2mqtt/Landing Switch/state_l2" };
> var landinglamps = flow.get('landinglamps') || 0;
> var newMsg = { topic: "Landing Lamp"};
> var landinglamp = flow.get("light.landing.lamp") || 0;
> 
> ```

This will just keep overwriting the value of **var newMsg** so it will only ever be the last value you set it to ?

[Next page](https://discourse.nodered.org/t/two-way-switch-infinite-loop/67115.md?page=2)
