Node-Red: Subscribing to dynamic topics programmatically (and acting upon topic updates!)


I’m working on a little project whereby I want to programmatically and dynamically subscribe to MQTT topics and be called upon when those topics are updated.

I can see that dragging the MQTT-In node onto a flow and configuring it for a dynamic subscription is feasible but I want to be able to programmatically do this, looping round a number of topics subscribing to them and be called upon when the topics update. Is this possible?

Alternatively, given a string topic, is it possible to “get” the current MQTT topic value in a function, programmatically?

Meanwhile, I’ll continue my search…

(still learning what’s possible with NodeRed… trying to run before I can walk!)

I’m not sure if I understood your question correctly but for the second part you should have the topic in msg.topic and do whatever you need with it.

L.E.: I think I figured out what you want to do. If your payload is in fact a set of values you want to be able to iterate through them and run some actions but the size of the set is dynamic.

I do something similar with my Tradfri devices which are still on their own hub. The Tradfri library has a status node where I can select as many devices as I want and I use it to check battery levels. Since for functions you need to set a fixed amount of output values this wasn’t very useful. What I ended up doing was to use a split node to split msg.payload into multiple flows (basically iterate through the array of devices). You can then use a function node to process each payload by itself.

I guess I’m trying to avoid having a flow that is fixed/hard coded for the set of devices I have connected to Core and accessible via MQTT to feed my little project - playing with the Sonoff NSPanel (which I’ve flashed with different firmware to allow for MQTT communication). This approach would however I guess free me up to continue with my little adventure… and prove I can get it too work! :thinking::sunglasses:

What you’re probably looking for are topic subscriptions of the form:


The above would then get all messages which begin with “mytopic/”. There are other types of patterns as well which can be more selective in case there’s a lot of subtopics and you only want those ending in eg “/config” as the fourth level:


Once you receive a message you then filter on the content of msg.topic, either by string or for example regex

Thanks. I had considered that but the topic names are based on the Zigbee device names so would be a bit of a mare to filter on. I’m going with the hardcoded approach for now to prove this can work… feels like I’m making progress!

That’s what regex is for :wink:


1 Like