MQTT topic from .env

Hi,

I have a device containing many sensors, the sensors will publish their data to the topic such as
"/device_1/temperature". The problem is that I will have many devices with different id such as "device_2, device_n".

The same mqtt flow will run on each device, so they will have different config/env files, so it is bad idea to hardcode the device id in my current node-red flow, every time a new device is configured, I have to manually change the topic.

So I'm looking for a way to make the mqtt in/out nodes to subscribe/publish to different topics based on the device_id configured in the config or .env files, such as "/{device_id}/temperature".

Any helps would be appreciated!

  1. MQTT does have a dynamic-IN option so you can specify the TOPIC to whatever you want
  2. you can load the topic from your own created config file
1 Like

You can use environment variables. See Using environment variables : Node-RED

You can define these in a file called environment in the .node-red folder (or wherever your node red user directory is). Then for MQTT Out nodes you can use the environment variable to build the topic that you send to the node. If you need MQTT In nodes then you can either subscribe using wild cards so you pick up all device topics and then use a Switch node to select the ones of interest, or use Dynamic subscription as suggested by @xx_Nexus_xx. Or you could put the full topic in the environment file and use that in the MQTT In node.

1 Like

I see your topics have leading slashes, this is generally considered a bad thing.

Perhaps the first level of your topic should be some sort of application name eg livesensors/device_1/temperature. Then your subscription topic need not start with the + wildcard and the broker can also manage other applications - devsensors/device_42/temperature or reactor/1/core/temperature

1 Like

Hi, thanks for the help, the dynamic option works, but I have around 200 mqtt in/out nodes for now, so it's going to be very messy if add an inject node for each mqtt node. Is it possible to set a dynamic topic on the mqtt node directly?

as mentioned by @Colin you can use the ENVIRONMENT variable directly (I have not tried myself)
image

why would you have 200 in/out nodes ?

  1. I only have a single MQTT-out.. and set the topic with the normal change-node
    image
  2. I only have a single MQTT-IN..followed by switch node managing all topics
    image

With above approach I'm managing over 100 zigbee devices .. and it is easy to debug any issues

Thanks for helping~

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