Global vars for OH3 Rules?

Did I miss something or is there no way to define a global var in NGRE?

This would lead to unusable functions (for example Timers could not be cancelled any longer).

what language are you using? for ECMA, to keep variables alive between runs, assign them to this. :slight_smile:

this.myTimer = (this.mytimer === undefined) ? null:this.myTimer;

this.myTimer = ScriptExecution.createTimer(ZonedDateTime.now().plusMinutes(1), function(){
                  // do something
                  this.myTimer = null;
                });

Yes thats correct :slight_smile: Here some further reading: OH 3 Examples: Writing and using JavaScript Libraries in MainUI created Rules

Just to summarize, there are two questions here.

  1. Defining global variables: cannot be done in the UI. All variables are only available in the Script Action/Condition they are defined in. For global variables (i.e. variables that can be used and modified from multiple rules) you have to define the rules in a .js file and defined the variables in that same file outside the rules, just as you do with .rules files.

  2. Preserving a variable from one run of a Script Action to the next: Do as Tom demonstrates. The ternary operator checks to see if the variable already exists or not. If not it initializes it to null. If it does, it continues to use what ever it was set to before the rule ran, which in this case could be the Timer that was created the last time the rule ran.

1 Like