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".
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.
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
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?