Can I create / call context.name[variable]

I am creating a node that will monitor ON duration for many switches under MQTT control. Is there a way to create / identify context like this? Switch behavior can happen in any random sequence (ie: SW 1 OFF, SW 4 ON, SW 2 OFF).

Code sample below created to illustrate what I'm trying to do, not actual code.

> device = msg.device;            // this is the switch number
> state  = msg.payload;           //  "ON"  or "off"
> context.timer[device] = new Date().getTime();          // ms
> context.state[device] = state;
> 
> if (state === 'off') duration[device] = new Date().getTime() - context.timer[device];

TIA st

Please check the Node-RED official documentation first.

https://nodered.org/docs/user-guide/context

What makes you think I didn't? And before you tell me to search the forum, I've done that. And before you tell me to search the internet, I've done that.

But hey, thanks for responding anyway.

I was going to say that the page that I shared answers your question explicitly. However, that isn't quite accurate, it links to the function page which has this section on using context which DOES explicitly answer your question.

https://nodered.org/docs/user-guide/writing-functions#storing-data

To answer that question, your syntax is wrong, so one would assume you never read the documentation.

I bow to you and offer my thanks.

I understand the use of set and get with saving context (global or flow) but never thought about (related them to) creating a simple node local context.

Node-red continues to amaze me.

1 Like

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