Dynamic node instantiation

I run a relatively complex heating control flow which controls a boiler and a set of TRVs in each zone.
I use a list of zones in flow.context and inject/split combo to generate messages for each zone, they trigger functions and eventtually call call.service(trv_{{zone_name}}) to make home assistant adjust the TRV. So far so good.

I want to use PID node to control the TRVs. PID is stateful so I have to have an instance of the node for each zone.

Obviously I can create a set of PID nodes per zone and somehow route messages to the appropriate one but this is ugly. I'd like to have a way to instantiate a node programmatically and to do in the function something like:
(sorry for pythonic code)

pids=flow.get('mypids')
if not msg.zone in pids.keys():
          pids[msg.zone] =  Pid()
call pids[msg.zone](msg)

so that I don't have an ugly hardcoded list of nodes?

Welcome to the forums @avk999

There is no way to do this within a flow easily - if you really really really wanted to however, you will need to use the HTTP API's to programatically modify your flows and that is going to be a monstrous ordeal.

With that said......

There maybe a way to do it through the use node modules.

in settings.js, add a pid module (example below)

functionGlobalContext: {
     pid:require('node-pid-controller'),
},

Then in your JS function

const pids=flow.get('mypids')
if (!pids[msg.zone]){
    pids[msg.zone] = new global.get('pid')({...})
} 

I don't have any experience with PID - but the link-call node maybe useful also.

1 Like

Thank you, that looks promising.
For now I'm thinking of forking the PID node (node-red-contrib-pid) to make it have a hasharray of state objects but your approach looks better.

1 Like

Before going down that complex route, you might want to take a look at sub-flows.

A subflow is simply a section of flow that, when added to your flows, creates another instance of itself. Sub-flows allow setting of local environment variables as well so you should be able to easily pass through the appropriate device ID's, etc.

Obviously, this isn't fully dynamic by any means but it may be a stepping stone for you.

Of course, there may be other options as well.