# MQTT Dynamic subscription disconnects after switching brokers

**URL:** <https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786>\
**Category:** General\
**Created:** [26 April 2022 09:20 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786 "2022-04-26T09:20:18Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![lill17](https://avatars.discourse-cdn.com/v4/letter/l/e0b2c6/32.png) [@lill17](https://discourse.nodered.org/u/lill17)\
**Post date:** [26 April 2022 09:20 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/1 "2022-04-26T09:20:18Z")

</div>

Hello!  
Currently my flow has the funcitonality of switching brokers dynamically directly from the dashboard. This works and i am able to connect to multiple brokers on the fly.

The only real problem i have is if i were to connect to a broker i were previously connected to it will connect but it will disconnect a few seconds after.

Im running the MQTT node with clean sessions (although im unsure if this actually works when running it dynamically).

Any thoughts or ideas of what might cause this issue?

EDIT: The error seems to only occur when i attempt to connect to a broker that doesnt exist and then go back to a broker ive previously been connected to.

---

<div class="post-metadata">

**Author:** ![Shan](https://avatars.discourse-cdn.com/v4/letter/s/7ab992/32.png) [@Shan](https://discourse.nodered.org/u/Shan)\
**Post date:** [26 April 2022 09:27 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/2 "2022-04-26T09:27:50Z")

</div>

I seem to be having the same problem. I am assuming the connection from the previous flows keeps lingering.

---

<div class="post-metadata">

**Author:** ![lill17](https://avatars.discourse-cdn.com/v4/letter/l/e0b2c6/32.png) [@lill17](https://discourse.nodered.org/u/lill17)\
**Post date:** [26 April 2022 10:04 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/3 "2022-04-26T10:04:20Z")

</div>

I believe i found what is causing the issue, i still dont know why. Mine seems to only start disconnecting after ive tried to connect to a non-existing broker. Is it the same for you?

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [26 April 2022 10:14 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/4 "2022-04-26T10:14:58Z")

</div>

@Shan@lill17

Can you both please share a **minimal** flow that demonstrated this issue.  
Also, include step by step instructions on how to re-create the issue.

#### minimal flow...

Please use only standard nodes (i.e. use inject nodes instead of dashboard buttons, use constants instead of flow/global context) otherwise I wont be able to test / fix the issue.

---

<div class="post-metadata">

**Author:** ![Shan](https://avatars.discourse-cdn.com/v4/letter/s/7ab992/32.png) [@Shan](https://discourse.nodered.org/u/Shan)\
**Post date:** [26 April 2022 10:19 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/5 "2022-04-26T10:19:07Z")

</div>

No, I do not have such a problem. I have both my brokers available

---

<div class="post-metadata">

**Author:** ![lill17](https://avatars.discourse-cdn.com/v4/letter/l/e0b2c6/32.png) [@lill17](https://discourse.nodered.org/u/lill17)\
**Post date:** [26 April 2022 10:31 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/6 "2022-04-26T10:31:02Z")

</div>

I'll try though i am unsure how to provide that for you, ive copied the flow  
Here you go:

```auto
[
    {
        "id": "55525a9d18c99b86",
        "type": "tab",
        "label": "test flow",
        "disabled": false,
        "info": "",
        "env": []
    },
    {
        "id": "23d57f61ddd34935",
        "type": "mqtt in",
        "z": "55525a9d18c99b86",
        "name": "Broker node",
        "topic": "",
        "qos": "2",
        "datatype": "auto",
        "broker": "30454c673e913e36",
        "nl": false,
        "rap": true,
        "rh": 0,
        "inputs": 1,
        "x": 710,
        "y": 160,
        "wires": [
            []
        ]
    },
    {
        "id": "e2b9ba3bf294a263",
        "type": "function",
        "z": "55525a9d18c99b86",
        "name": "Connect to existing broker",
        "func": "\nconst new_broker = {broker: \"192.168.0.100\", port: \"1883\", username: \"sub\", password: \"\", force: \"true\"};\n\nmsg.action = \"connect\";\nmsg.broker = new_broker;\n\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 450,
        "y": 100,
        "wires": [
            [
                "23d57f61ddd34935"
            ]
        ]
    },
    {
        "id": "4639b22bf3c59f41",
        "type": "inject",
        "z": "55525a9d18c99b86",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "",
        "payloadType": "date",
        "x": 240,
        "y": 100,
        "wires": [
            [
                "e2b9ba3bf294a263"
            ]
        ]
    },
    {
        "id": "edfa1ec2bf2fc991",
        "type": "function",
        "z": "55525a9d18c99b86",
        "name": "Connect to existing broker",
        "func": "\nconst new_broker = {broker: \"192.168.0.101\", port: \"1883\", username: \"sub\", password: \"\", force: \"true\"};\n\nmsg.action = \"connect\";\nmsg.broker = new_broker;\n\nreturn msg;\n",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 450,
        "y": 160,
        "wires": [
            [
                "23d57f61ddd34935"
            ]
        ]
    },
    {
        "id": "226b49c328f5063c",
        "type": "function",
        "z": "55525a9d18c99b86",
        "name": "Connect to non existing broker",
        "func": "\nconst new_broker = {broker: \"192.168.0.102\", port: \"1883\", username: \"sub\", password: \"\", force: \"true\"};\n\nmsg.action = \"connect\";\nmsg.broker = new_broker;\n\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 470,
        "y": 220,
        "wires": [
            [
                "23d57f61ddd34935"
            ]
        ]
    },
    {
        "id": "dd21943b30072aef",
        "type": "inject",
        "z": "55525a9d18c99b86",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "",
        "payloadType": "date",
        "x": 240,
        "y": 160,
        "wires": [
            [
                "edfa1ec2bf2fc991"
            ]
        ]
    },
    {
        "id": "c1070b307f33bd89",
        "type": "inject",
        "z": "55525a9d18c99b86",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "",
        "payloadType": "date",
        "x": 240,
        "y": 220,
        "wires": [
            [
                "226b49c328f5063c"
            ]
        ]
    },
    {
        "id": "30454c673e913e36",
        "type": "mqtt-broker",
        "name": "",
        "broker": "localhost",
        "port": "",
        "clientid": "",
        "autoConnect": false,
        "usetls": false,
        "protocolVersion": "5",
        "keepalive": "60",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthPayload": "",
        "birthMsg": {},
        "closeTopic": "",
        "closeQos": "0",
        "closePayload": "",
        "closeMsg": {},
        "willTopic": "",
        "willQos": "0",
        "willPayload": "",
        "willMsg": {},
        "sessionExpiry": ""
    }
]

```

![errrflow](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/e/6/e60d39c0d340196813a9e51adcdae9500b565672.png)

To replicate the issue; Press the injects for two existing brokers, you'll have to configure the dynamic information in the functions first. You can try to connect between two existing brokers and it should not be a problem, however if you connect to the third one (which shouldn't exist) then the connection to the other ones should start to get disconnected.

---

<div class="post-metadata">

**Author:** ![Shan](https://avatars.discourse-cdn.com/v4/letter/s/7ab992/32.png) [@Shan](https://discourse.nodered.org/u/Shan)\
**Post date:** [26 April 2022 10:33 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/7 "2022-04-26T10:33:24Z")

</div>

- I am connected to the `external-mqtt-broker` (which is the name of the docker container  

- Upon initializing the Flow, the pub/sub, unsubscribe work very well

- Once you try to disconnect from the broker and try to reconnect you will observe that the broker stays connected and then disconnected almost immediately

```json
[{"id":"26556d1175d20916","type":"inject","z":"274e9e14c00481bd","name":"Reconnect to Broker","props":[{"p":"action","v":"connect","vt":"str"},{"p":"broker","v":"{\"broker\":\"external-mqtt-broker\",\"port\":1883,\"force\":true}","vt":"json"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","x":570,"y":500,"wires":[["63b80c56732ac6e3","42fbe396dce216d3"]]}]

```

Let me know if you want me to reproduce a more concrete flow

### Broker Logs

It seems like

```auto
external-mqtt-broker | 1650969231: No will message specified.
external-mqtt-broker | 1650969231: Sending CONNACK to nodered_482a38c2f010fb7b (0, 0)
external-mqtt-broker | 1650969233: New connection from 172.28.0.4:34336 on port 1883.
external-mqtt-broker | 1650969233: Client nodered_30cc530cb1b76710 already connected, closing old connection.
external-mqtt-broker | 1650969233: New client connected from 172.28.0.4:34336 as nodered_30cc530cb1b76710 (p2, c1, k60)

```

Broker is closing the connection because it already has the same clientId from the flow

## Edit

I wasn't able to reproduce the bug again. It probably was my error since I didn't add  
`msg.broker` to

```json
{
  "broker": "external-mqtt-broker",
  "port": 1883,
  "force": true
}

```

In my initial inject node during setup

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [26 April 2022 11:01 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/8 "2022-04-26T11:01:59Z")

</div>

Thanks guys. I managed to re-produce the issue.

I have a fix that I publish for the next release (next few days hopefully).

Working demo...  
 ![chrome_9z24wI9isO](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/e/c/ec9e5b88c45faa6450e94d80148c459784b93620.gif)

---

<div class="post-metadata">

**Author:** ![lill17](https://avatars.discourse-cdn.com/v4/letter/l/e0b2c6/32.png) [@lill17](https://discourse.nodered.org/u/lill17)\
**Post date:** [26 April 2022 11:20 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/9 "2022-04-26T11:20:47Z")

</div>

I can't tell from the video that you actually managed to reproduce the issue (that i had atleast). After you connect to a non existing broker and proceed to connect to a existing broker, will it disconnect itself?

Demo here: [MQTT Disconnect issue - YouTube](https://www.youtube.com/watch?v=IT9hW2sronc)

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [26 April 2022 11:50 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/10 "2022-04-26T11:50:29Z")

</div>

> [@lill17](#):
>
> I can't tell from the video that you actually managed to reproduce the issue

Yes I did.

> [@Steve-Mcl](#):
>
> I managed to re-produce the issue

The GIF image titled "Working demo" was demonstrating it fixed/working

---

<div class="post-metadata">

**Author:** ![Shan](https://avatars.discourse-cdn.com/v4/letter/s/7ab992/32.png) [@Shan](https://discourse.nodered.org/u/Shan)\
**Post date:** [26 April 2022 12:24 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/11 "2022-04-26T12:24:11Z")

</div>

As a complete out-of-the-box example I have made this repository available [GitHub - shantanoo-desai/node-red-subflows-mqtt: Create Custom Nodes in node-red using subflows for MQTT Broker](https://github.com/shantanoo-desai/node-red-subflows-mqtt) fo you try out. I have a full report of disconnection drop outs in the Issues: [MQTT Connect / Disconnect from node-red · Issue #2 · shantanoo-desai/node-red-subflows-mqtt · GitHub](https://github.com/shantanoo-desai/node-red-subflows-mqtt/issues/2)

Please feel free to reach-out on this issue. I will use the repository to try and log scenarios where I am unable to keep the _dynamic_ nature of the MQTT nodes

---

<div class="post-metadata">

**Author:** ![lill17](https://avatars.discourse-cdn.com/v4/letter/l/e0b2c6/32.png) [@lill17](https://discourse.nodered.org/u/lill17)\
**Post date:** [26 April 2022 12:33 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/12 "2022-04-26T12:33:02Z")

</div>

Ah great, my bad! Thanks!

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [26 April 2022 15:16 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/13 "2022-04-26T15:16:59Z")

</div>

PR here: [Fix incorrect MQTT status by Steve-Mcl · Pull Request #3552 · node-red/node-red · GitHub](https://github.com/node-red/node-red/pull/3552)

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [10 May 2022 15:17 UTC](https://discourse.nodered.org/t/mqtt-dynamic-subscription-disconnects-after-switching-brokers/61786/14 "2022-05-10T15:17:29Z")

</div>

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