# Examples that publish/subscribe MQTT?

**URL:** <https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320>\
**Category:** Developing Nodes\
**Created:** [28 January 2019 01:26 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320 "2019-01-28T01:26:30Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![ScottChapman](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/scottchapman/32/4838_2.png) [@ScottChapman](https://discourse.nodered.org/u/ScottChapman)\
**Post date:** [28 January 2019 01:26 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/1 "2019-01-28T01:26:30Z")

</div>

I'm trying to create a couple of nodes that are basically publishing and subscribing to MQTT.

I've got them configured so that I get the MQTT broker info. But I am not getting the 'connect' event. My code basically looks like:  
module.exports = function (RED) {  
'use strict';

```
    function STCONFIG(config) {
        RED.nodes.createNode(this, config);
        this.broker = config.broker;
        this.brokerConn = RED.nodes.getNode(this.broker);
        const node = this;
        if (this.brokerConn) {
            this.status({fill: 'red', shape: 'ring', text: 'node-red:common.status.disconnected'});
            this.brokerConn.register(this);
            console.log("registered")
            this.brokerConn.on("connect", () => {
                console.log("CONNECTED")
                node.status({fill: 'green', shape: 'dot', text: 'node-red:common.status.connected'});
                publish(this.brokerConn,config.map)
                node.on('input', function(message) {
                    publish(this.brokerConn,msg.payload)
                });
            })
            this.on('close', done => {
                if (node.brokerConn) {
                    node.brokerConn.deregister(node, done);
                }
            });
            this.brokerConn.connect();
        } else {
            this.error(RED._('mqtt.errors.missing-config'));
        }
    }
    RED.nodes.registerType('st-presence-config', STCONFIG);
};

```

On my output, I get the 'registered' line, but NOT the 'CONNECTED'. I'm clearly doing something wrong. I am assuming that what I am getting here with `brokerConn` is an instance of `mqtt`?

Is there some documentation that describes how to build nodes that work with the MQTT brokers?

---

<div class="post-metadata">

**Author:** ![JayDickson](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/jaydickson/32/90592_2.png) [@JayDickson](https://discourse.nodered.org/u/JayDickson)\
**Post date:** [28 January 2019 01:31 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/2 "2019-01-28T01:31:35Z")

</div>

Is the built-in mqtt node somehow deficient for your purposes?

---

<div class="post-metadata">

**Author:** ![ScottChapman](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/scottchapman/32/4838_2.png) [@ScottChapman](https://discourse.nodered.org/u/ScottChapman)\
**Post date:** [28 January 2019 01:43 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/3 "2019-01-28T01:43:18Z")

</div>

Yes, I am building my own nodes that use MQTT in it's implementation.

(well, technically I could, but I want to build my own nodes to make things simpler...)

Basically is there anything documented (or examples) of nodes that use the embedded MQTT client?

---

<div class="post-metadata">

**Author:** ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)\
**Post date:** [28 January 2019 07:01 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/4 "2019-01-28T07:01:15Z")

</div>

> [@ScottChapman](#):
>
> Basically is there anything documented (or examples) of nodes that use the embedded MQTT client?

You will need to do a code review of the built-in MQTT nodes. They have everything you need in order to get started.

---

<div class="post-metadata">

**Author:** ![cflurin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/cflurin/32/29_2.png) [@cflurin](https://discourse.nodered.org/u/cflurin)\
**Post date:** [28 January 2019 10:37 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/5 "2019-01-28T10:37:08Z")

</div>

On GitHub (mqtt.js) there is a very simply example:

[https://github.com/mqttjs/MQTT.js#example](https://github.com/mqttjs/MQTT.js#example)

---

<div class="post-metadata">

**Author:** ![cymplecy](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/cymplecy/32/2773_2.png) [@cymplecy](https://discourse.nodered.org/u/cymplecy)\
**Post date:** [28 January 2019 10:58 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/6 "2019-01-28T10:58:40Z")

</div>

> [@ScottChapman](#):
>
> simpler

Interesting use of the word,given how existing NodeRED nodes are the simplest to use things for MQTT on the planet 🙂

---

<div class="post-metadata">

**Author:** ![ScottChapman](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/scottchapman/32/4838_2.png) [@ScottChapman](https://discourse.nodered.org/u/ScottChapman)\
**Post date:** [28 January 2019 18:49 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/7 "2019-01-28T18:49:48Z")

</div>

Thanks, I tried to do exactly that in my code above (though I actually added the connect statement like in that example). But I still never seem to get the "connect" event.

I also took a look at the built-in [node](https://github.com/node-red/node-red/blob/master/nodes/core/io/10-mqtt.js#L427-L470) it never actually calls connect. But in my case when it enters my function the `brokerConn` is never connected. What is odd is that the status on the flow shows up as green and connected. But that doesn't appear to be because of my code...

I'm clearly missing something...

---

<div class="post-metadata">

**Author:** ![ScottChapman](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/scottchapman/32/4838_2.png) [@ScottChapman](https://discourse.nodered.org/u/ScottChapman)\
**Post date:** [28 January 2019 18:50 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/8 "2019-01-28T18:50:17Z")

</div>

Building more of a turn-key solution.

---

<div class="post-metadata">

**Author:** ![ScottChapman](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/scottchapman/32/4838_2.png) [@ScottChapman](https://discourse.nodered.org/u/ScottChapman)\
**Post date:** [28 January 2019 19:21 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/9 "2019-01-28T19:21:14Z")

</div>

Oh, I should say that what I am attempting to do is to leverage the (apparent) MQTT connection pooling that (appears) to be built into NodeRed.

I'm pretty sure I could just "roll my own" connection but that seems like the wrong approach...

---

<div class="post-metadata">

**Author:** ![cymplecy](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/cymplecy/32/2773_2.png) [@cymplecy](https://discourse.nodered.org/u/cymplecy)\
**Post date:** [28 January 2019 22:21 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/10 "2019-01-28T22:21:06Z")

</div>

I'm no expert (at all) but I think that some things that are available to core nodes might not be available to contrib ones

So its possible you might come against a hard wall trying to reuse core code into a contrib one

---

<div class="post-metadata">

**Author:** ![knolleary](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/knolleary/32/3_2.png) [@knolleary](https://discourse.nodered.org/u/knolleary)\
**Post date:** [28 January 2019 22:49 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/11 "2019-01-28T22:49:30Z")

</div>

> [@cymplecy](#):
>
> I'm no expert (at all) but I think that some things that are available to core nodes might not be available to contrib ones

Nope - the core nodes are on a pretty level playing field with anything else. The only exceptions are the Link, Status and Catch nodes are they have more fundamental runtime behaviour.

The challenge here is more the mqtt-broker node hasn't been written to be a generically reusable mqtt client node. It serves the needs of the mqtt-in and mqtt-out nodes, which may or may not be all that is needed.

Having spoken to Scott on slack, his node needs to know specifically when the connection comes and goes - something the core mqtt nodes don't care about themselves. So the mqtt-broker node doesn't expose it directly. I have shown him how to access the raw mqtt client used by the mqtt-broker node to access the finer-grained events he needs.

That does put more of a burden on us not to change the internal implementation of the node; I'd prefer it if this was raised as a more general requirement and a proper design put in place that we could have confidence of in the longer term...

---

<div class="post-metadata">

**Author:** ![ScottChapman](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/scottchapman/32/4838_2.png) [@ScottChapman](https://discourse.nodered.org/u/ScottChapman)\
**Post date:** [29 January 2019 00:50 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/12 "2019-01-29T00:50:29Z")

</div>

Thanks. Yea, I am not in favor of just leveraging the implementation directly.

I suppose one option would be to expose some functionality (like events for 'connect'). But even then it would be pretty hard for someone to write a node that leveraged it since it is possible for the connection to be established before the node is called (seems unlikely, but there is basically a race condition).

I think for my particular case I may as well just manage my own connection since I shouldn't need it around for very long so I think I can take care of it.

---

<div class="post-metadata">

**Author:** ![ScottChapman](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/scottchapman/32/4838_2.png) [@ScottChapman](https://discourse.nodered.org/u/ScottChapman)\
**Post date:** [29 January 2019 14:34 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/13 "2019-01-29T14:34:08Z")

</div>

So I had some thought on my drive in (it's not a long drive, so I haven't thought this through completely!).

It is clear that there is an attempt to allow custom nodes to share MQTT connections within Node Red; I think this is great. But for reasons above it is not possible for custom nodes to know when the connection changes.

I think this could be addressed by doing just two things:

1. Promoting connection related events to all registered nodes
2. When a node is registered, fire the current connection state to the newly registered node.

Thoughts?

---

<div class="post-metadata">

**Author:** ![drmibell](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/drmibell/32/8424_2.png) [@drmibell](https://discourse.nodered.org/u/drmibell)\
**Post date:** [29 January 2019 17:52 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/14 "2019-01-29T17:52:22Z")

</div>

> [@knolleary](#):
>
> Nope - the core nodes are on a pretty level playing field with anything else. The only exceptions are the Link, Status and Catch nodes are they have more fundamental runtime behaviour.

Nick, thanks for the clarification. I think I ran into this while trying to embed the `link` node functionality in a custom node. The ui looked ok, but no events were passed. Is this a deliberate design choice? likely to be a permanent limitation?

---

<div class="post-metadata">

**Author:** ![ScottChapman](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/scottchapman/32/4838_2.png) [@ScottChapman](https://discourse.nodered.org/u/ScottChapman)\
**Post date:** [29 January 2019 18:10 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/15 "2019-01-29T18:10:02Z")

</div>

Wow, so I refactored my node to basically manage it's own `mqttjs` client (I create my client after obtaining the brokerConn URL & options).

I basically connect, and once I get the connected event I publish my message.

To test, I have a simple flow with my config node, along with an `MQTT In` node on the topic so I can verify it's posting properly:

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/2X/f/ff642717f02a67fceeb554320111b2b20484be64.png)

I am connecting to the MQTT on the local host.

What is happening when I run is I can basically see my connections ping-ponging between the two. One connects and the other disconnects, then it switches. Back and forth...

Any idea what's going on with that?

---

<div class="post-metadata">

**Author:** ![dceejay](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/dceejay/32/38_2.png) [@dceejay](https://discourse.nodered.org/u/dceejay)\
**Post date:** [29 January 2019 18:49 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/16 "2019-01-29T18:49:37Z")

</div>

That typically happens if you use the same clientid for both connections

---

<div class="post-metadata">

**Author:** ![ScottChapman](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/scottchapman/32/4838_2.png) [@ScottChapman](https://discourse.nodered.org/u/ScottChapman)\
**Post date:** [29 January 2019 19:59 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/17 "2019-01-29T19:59:26Z")

</div>

Yup. fixed!

---

<div class="post-metadata">

**Author:** ![scottpageindysoft](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/scottpageindysoft/32/13107_2.png) [@scottpageindysoft](https://discourse.nodered.org/u/scottpageindysoft)\
**Post date:** [1 October 2019 03:41 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/18 "2019-10-01T03:41:19Z")

</div>

I hate to wake an old thread, but this is the only info I've found accessing the MQTT broker client connection inside of a custom node.  
I have a similar requirement as the OP. I'm not quite following what you were talking about in your post about talking to Scott and helping him get to a solution.

Is there a way for me to publish/subscribe from within a custom node's code-behind?  
My entire project is based around MQTT, and having to string dozens, or even hundreds, of MQTT in/out nodes everywhere, is far too much boilerplate. I would love to be able to roll my own nodes, and just access the existing MQTT client connection to let it handle the work.

Is this possible or am I just missing the solution in the above conversations?

Thanks!

---

<div class="post-metadata">

**Author:** ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)\
**Post date:** [1 October 2019 14:22 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/19 "2019-10-01T14:22:38Z")

</div>

I think that what Nick was saying was simply that currently, you have to replicate what the mqtt in/out nodes do internally. If you use the same MQTT library, you can reuse much of the code through copy/paste into your own node.

Just make sure that you make the client id unique for every node instance.

---

<div class="post-metadata">

**Author:** ![scottpageindysoft](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/scottpageindysoft/32/13107_2.png) [@scottpageindysoft](https://discourse.nodered.org/u/scottpageindysoft)\
**Post date:** [1 October 2019 14:38 UTC](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320/20 "2019-10-01T14:38:08Z")

</div>

Yep, makes perfect sense.  
At least I can reuse the configuration node connection.  
Thanks!

[Next page](https://discourse.nodered.org/t/examples-that-publish-subscribe-mqtt/7320.md?page=2)
