I'm trying to use an MQTT broker to broadcast some data.
For flexibility, I want to set the MQTT variables in the system environment and then read them
in my Node-Red flow. It used to work (some years ago) but no longer does. Here's a simple example
showing this.
Working context:
Node-RED version: v3.1.6
Node.js version: v18.19.1
Linux 6.1.0-rpi7-rpi-v8 arm64 LE
(1) Check that the environment variables are set:
user@RP01:~$ set | grep MQTT
which returns
MQTT_BROKER=broker.hivemq.com MQTT_CLIENT_ID=Client007 MQTT_NAME=MyName MQTT_PORT=1883 MQTT_TOPIC=ViewMe/Meter01
(2) Based on what I found searching the Internet (and possibly not the right thing to do),
here's the (only) change I made to settings.js in the ~/.node-red directory:
functionGlobalContext: {
// os:require('os'),
env: process.env,
},
(3) Now start Node-Red
user@RP01:~$ node-red-start
which returns
Start Node-RED
...[snipped]...
Starting as a systemd service.
(4) Run the following flow in a browser.
Flow to display the MQTT variables:
[
{
"id": "98320a06c471a025",
"type": "tab",
"label": "Flow 3",
"disabled": false,
"info": "",
"env": []
},
{
"id": "179e115a0c5b7eae",
"type": "function",
"z": "98320a06c471a025",
"name": "View MQTT variables",
"func": "msg.payload = \"MQTT_BROKER: '\" + env.get('MQTT_BROKER') +\"' \\n\";\nmsg.payload = msg.payload + \"MQTT_PORT: '\" + env.get('MQTT_PORT') +\"' \\n\";\nmsg.payload = msg.payload + \"MQTT_TOPIC: '\" + env.get('MQTT_TOPIC') +\"' \\n\";\nmsg.payload = msg.payload + \"--- following are not used ---\" + \" \\n\";\nmsg.payload = msg.payload + \"MQTT_CLIENT_ID: '\"+ env.get('MQTT_CLIENT_ID') + \"' \\n\";\nmsg.payload = msg.payload + \"MQTT_NAME: '\" + env.get('MQTT_NAME') +\"' \\n\";\nreturn msg;\n",
"outputs": 1,
"timeout": "",
"noerr": 0,
"initialize": "",
"finalize": "",
"libs": [],
"x": 360,
"y": 80,
"wires": [
[
"3e6758c2883dfd69"
]
]
},
{
"id": "3e6758c2883dfd69",
"type": "debug",
"z": "98320a06c471a025",
"name": "",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "false",
"x": 570,
"y": 80,
"wires": []
},
{
"id": "f37e16fcb00b5f1a",
"type": "inject",
"z": "98320a06c471a025",
"name": "",
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "true",
"payloadType": "bool",
"x": 130,
"y": 80,
"wires": [
[
"179e115a0c5b7eae"
]
]
}
]
The result is
msg.payload : string[178]
"MQTT_BROKER: 'undefined' ↵MQTT_PORT: 'undefined' ↵MQTT_TOPIC: 'undefined' ↵--- following are not used --- ↵MQTT_CLIENT_ID: 'undefined' ↵MQTT_NAME: 'undefined' ↵"
I.e., everything is undefined.
Many thanks for help in figuring this out.
~ThisEndUp.