Dynamic broker connection - best practice

I want to efficiently connect and subscribe to a mqtt broker in 1 go.

I have the following in a function node:

const action = ["disconnect","connect","subscribe"]
const force = true
const topic = "zigbee2mqtt/#"
const broker = {}

broker.broker = "10.0.0.172"
broker.port = 1883
broker.username = "username"
broker.password = "pwd"

msg.broker = broker
msg.force = force
msg.topic = topic

action.forEach(action=>{
    msg.action = action
    node.send(msg)
})

return null

Besides the convoluted way of first connecting and then subscribing to a topic, when i push this through an mqtt node it will fail, because the connection may need to disconnect first which takes some time, so I will always be bound to some form of delay (and really I should first check for the response before continuing, which could introduce a potential loop).

Is there a simple no-nonsense way to dynamically connect/subscribe to a broker/topic.
It would be wonderful if one could just subscribe to a topic and the dynamic subscription just assumes to disconnect/connect itself first via some option.

Ok I am dumb, it already exactly does what i want: just subcribe.

1 Like