Monitoring state of a value in the Context

Is the following polling for value the correct way to get a message for each change in value of a key in the Context?


How expensive is it in terms of load (with an interval of 0.1 sec and with a dozen of flows monitoring the same value)?

Or is there a better practice?

Correct? Well not really. But currently the only way without doing something a bit more radical.

Currently, the context handlers don't produce events when something changes so you can't easily watch for a change and so polling is the only other option.

However, probably what most people do is to write the value out to an MQTT topic at the same time. Then you can watch for changes since you can subscribe to the topic.

Of course, in the simple example you've used, the "Node-RED way" would be to pass the true/false straight to your rbe node. Using flags is only for more complex flows where you need to control an input msg via a separate variable that is set by a different part of your flow. Even then, the flag variable would normally be queried as part of your main flow. So a msg comes in, it is sent to a change node that adds the flag from the variable and then is sent on to a switch node.

1 Like

Or in fact dispense completely with global and flow context and use retained topics in MQTT instead, which some believe (well me anyway) is usually a better way.

1 Like

Or use link nodes to pass the messages directly between tabs.


link nodes were what I was using extensively, but there is no way to link to nodes inside subflows, so I went with the Context.

MQTT is a very intriguing idea and a likely solution. Somehow I missed the fact that I could use it as a data store.

However, in the meantime, I started to take advantage of the persistent context. Do MQTT retained topics survive broker's restart?

They do if you have configured the broker to do so.

1 Like

Mosquitto docs say:

autosave_interval seconds
The number of seconds that mosquitto will wait between each time it saves the in-memory database to disk. If set to 0, the in-memory database will only be saved when mosquitto exits or when receiving the SIGUSR1 signal. Note that this setting only has an effect if persistence is enabled. Defaults to 1800 seconds (30 minutes).

Why is the default so large? Compared to Node-RED's 30 seconds for persistent storage...

It only matters if the pi is powered down without warning or crashes as it will be saved on a normal power down when mosquitto is closed.

1 Like

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