How do I set and then reference a global variable in an expression?

I'm using Node Red 13.5.3 in Home Assistant and using a call service node that is part of the Home Assistant "node package" (not sure what the proper term is).

I want to set my shades to not close all the way in the winter so condensation doesn't build up.

Currently, if I want to set the shades to a certain setting I use the expression {"position": 5 in the call-service node when calling the set_cover_position service in Home Assistant.

Instead of manually changing every single node to {"position": 5} and then to {"position": 0} when I want them to fully close again in the spring, I would like to set something (maybe it is called a Global Variable, I'm not sure, that's what I've tried so far). So instead of the expression {"position": 30}, I would do something like {"position": GLOBAL_VARIABLE}. Then I could change that global variable in one location and it would essentially update it for all nodes that reference it.

I tried to declare a global variable by typing global.set("shade_closed_setting", "5") in a function node. I'm not sure how to tell if I was successful or not.

Then I've just been guessing and testing to try to get it to work in the expression, but I have not been successful.
Some of the things I've tried:
{"position": global.get("shade_closed_setting")}
{"position": "global.shade_closed_setting"}
{"position": global.shade_closed_setting}

And I feel like I could keep guessing and testing forever. Unfortunately, I don't know any programming languages, which is probably the issue here.

You would select JSONata J: from the type input. Then you can use

{"position": $globalContext("shade_closed_setting")}

[edit] fixed typo

Thank you, this allowed me to figure it out. The exact code you provided didn't work, but the debug node said "Did you mean $globalContext?" so I put the $ sign in and it worked!

Also, it needed it still as the expression rather than the JSON.

{ "position": $globalContext("shade_closed_setting")}
is the code that worked in the end

with
global.set("shade_closed_setting", 5)
in the function node in the "On Start" tab.

Thanks again!

Yes I said use JSONata J: not JSON.

Glad you sorted it and figured out my typo in the example code. I corrected it above as to not mislead others.

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