I have a few flows that are working for starting and stopping a generator through a relay. One flow checks to see if the generator has quit (running out of fuel) and then de-energizes the relay.
What I would like to do is create a global context variable (I think) called FuelTankStatus to keep track of whether the generator has quit after running out of fuel, so that my auto-start flow doesn't try to start the generator. Then I would have an inject button or perhaps a toggle switch on a dashboard (once I start toying with that) to click when I fill the generator and then set the FuelTankStatus appropriately.
What is the best way to accomplish this? Perhaps a flow that simply has a function and which creates a var = a global.get("FuelTankStatus") and then checks to see if the value is null, and if so, assigns it an initial value?
In retrospect, I could have done away with the switches here and just combined both functions into 1 to accomplish the same thing....learning all the time lol
Also I started with globals, but eventually changed it to flow context since global wasn't necessary. If you change "flow" to "global" then you will have a global.
I also know I've seen other examples where people just use a switch node to create a global/flow variable. Probably just depends on what you're comfortable with.
If, in a function, you want to initialise a global context variable that may not yet have been created then you can use let fuelTankStatus = global.get("FuelTankStatus") ?? someInitialValue
The ?? tests for null or undefined, so this will create fuelTankStatus with the value of the context variable if it exists, or whatever initial value you have specified if it does not exist.
However, if you always want to initialise it to some value when node-red is restarted then use an Inject node that fires on startup and feed it into a Change node that sets the context variable to its initial value.
Finally though, please try and avoid global and flow context, it is very rarely necessary. Do it the node red way and feed the status to whatever nodes need it using messages.